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

  • 相关阅读:
    12.如何设置ulimit
    11.vim常用操作
    01Java jdk环境配置
    css
    Html
    day07 Class_field_method_反射
    JDBC
    Oracle day05 索引_数据去重
    Oracle day05 建表_约束
    Oracle day04 DML_事务_序列_视图_数据类型_DDL
  • 原文地址:https://www.cnblogs.com/sun-rain/p/5722003.html
Copyright © 2011-2022 走看看