码迷,mamicode.com
首页 > 编程语言 > 详细

多线程的效率一定快吗?

时间:2016-07-31 00:10:44      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

测试串行执行和并行执行:

 

//必须是final,否则会报错
    private static final long count = 100000000;
    
    @Test
    public void testEfficiency() throws Exception {
        
        serial();         //串行
        concurrence();         //并行
    }

    private void concurrence() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread t = new Thread(new Runnable() {
            
            @Override
            public void run() {
                int a = 0;
                for(long i =0;i<count;i++){
                    a ++;
                    a ++;
                    a ++;
                }
                
            }
        });
        
        t.start();
        
        int b = 0;
        for(long i = 0;i<count;i++){
            b --;
            b --;
            b --;
        }
        t.join();
        
        long end = System.currentTimeMillis();
        System.out.println("并行执行时长:"+(end - start));
        
    }

    private void serial() {
        long start = System.currentTimeMillis();
        int a = 0;
        for(long i=0;i<count;i++){
            a ++;
        }
        int b = 0;
        for(long i=0;i<count;i++){
            b --;
        }
        long end = System.currentTimeMillis();
        System.out.println("串行执行时长:"+(end - start));
    }

 

结果:

循环次数

串行时长

并行时长

100万

0

16

1000万

15

16

1亿

109

63

并发执行的效率不一定比串行执行高,因为多线程在执行的时候会有个抢占CPU资源,上下文切换的过程。

 

IT技术和行业交流群 417691667

 

多线程的效率一定快吗?

标签:

原文地址:http://www.cnblogs.com/sun-rain/p/5722003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!