多线程运行程序的目的一般是提高程序运行效率并且能够提高硬件的利用率比如多核CPU,但是如果我们只有单核CPU并发运行程序会怎样呢?
我以两个环境作为对比:
环境A(我本机8c)
环境B(我的云服务器1c)
分别运行并发、串行需要CPU参与的代码
这里需要注意,如果我运行Thread.sleep这种代码,是无法达到效果的,因为sleep时会让出cpu资源,cpu并没有参与工作。
上代码:
@Override
public void run(ApplicationArguments args) throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); Date begin = new Date(); new Thread(() -> { oneSecTime(); countDownLatch.countDown(); } ).start(); new Thread(() -> { oneSecTime(); countDownLatch.countDown(); } ).start(); while(true){ if(countDownLatch.getCount() == 0){ Date end = new Date(); System.out.println(end.getTime()-begin.getTime()); break; } } Date begin2 = new Date(); long a = 0; a = oneSecTime(); a += oneSecTime(); Date end2 = new Date(); System.out.println("a:"+a+" time:"+(end2.getTime()-begin2.getTime())); } private long oneSecTime(){ long f = 0; for (int i = 0; i < 10000; i++) { for (int j = 0; j < 100000; j++) { for (int k = 0; k < 10; k++) { f++; } } } return f; }
两个环境之间的差异请忽略,CPU型号本身不同
环境A:
6431
a:20000000000 time:9747
环境B:
5033
a:20000000000 time:56
能够看出来一点,多核环境下,多线程程序运行速度是较串行快的
但是单核环境下,多线程程序运行速度不快反而慢的多,CPU调度多线程上下文切换等消耗影响很严重。
这里简单记录一下,以打消自己心中疑惑