0
点赞
收藏
分享

微信扫一扫

多线程和串行化比较

洒在心头的阳光 2022-01-14 阅读 44

多线程一定比串行化快码?

答案是否定的,在任务量不大的时候串行化比多线程更快,当任务量大时多线程的优势才能显示出来。

例子,分别定义一个多线程方法和串行化方法来测试执行同一个任务花费的时间。

package com.teasir.concurrent;

public class ConcurrencyTest {
    private final static long count = 100000000;

    public static void main(String[] args) throws InterruptedException {
        concurrency();
        serial();

    }


    public static void concurrency() throws InterruptedException {
        long startTm = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (int i = 0; i < count; i++) {
                    a += 5;
                }
            }
        });
        thread.start();
        int b = 0;
        for (int i = 0; i < count; i++) {
            b--;
        }
        thread.join();
        long endTm = System.currentTimeMillis();
        System.out.println("concurrency的时间:" + (endTm - startTm)+"ms");
    }

    public static void serial() {
        long startTm = System.currentTimeMillis();
        int a = 0;
        for (int i = 0; i < count; i++) {
            a += 5;
        }
        int b = 0;
        for (int i = 0; i < count; i++) {
            b--;
        }
        long endTm = System.currentTimeMillis();
        System.out.println("senial的时间:" + (endTm - startTm)+"ms");
    }
}

测试结果

  循环次数	多线程   	串行化   
  10亿 	    1218ms	   1516ms
  1亿  	    118ms 	   195ms 
  1千万 	21ms  	   27ms  
  1百万 	18ms  	   8ms   
  108ms   	   5ms   

从测试结果可以分析出,当循环次数达到千万级别时,开启多个线程的执行任务速度才比串行化快,循环次数越多多线程的优势越明显。百万次循环内串行化的速度比多线程快是因为创建线程和线程间切换上下文会有时间开销。

举报

相关推荐

0 条评论