zoukankan      html  css  js  c++  java
  • 多线程的效率一定快吗?

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

    //必须是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

  • 相关阅读:
    Cmakelist.txt
    rename 后缀
    vector list array deque
    Primary Expression
    9 css中通用选择器的用法
    8 css中包含选择器的用法
    7 css中子选择器的用法
    6 id选择器的用法
    5 css类选择器的使用
    4 css外部链接式写法
  • 原文地址:https://www.cnblogs.com/sun-rain/p/5722003.html
Copyright © 2011-2022 走看看