在开发的过程中,多线程一直很受欢迎,因为它的运行速度比串行要快,但是到底快多少呢?一定快么?下面我们用一段代码来测试下
private static final long count = 100000;
public static void main(String[] args) throws InterruptedException {
concurrency();
serial();
}
public static void concurrency() throws InterruptedException{
long start = System.currentTimeMillis();
Thread thread = new Thread(new Runnable() {
public void run() {
int a = 0;
for(long i = 0;i < count;i++){
a += 5;
}
}
});
thread.start();
int b = 0;
for(long i = 0;i < count;i++){
b--;
}
thread.join();
long time = System.currentTimeMillis() - start;
System.out.println("concurrency : " + time + "ms,b = " + b);
}
public static void serial(){
long start = System.currentTimeMillis();
int a = 0;
for(int i=0;i<count;i++){
a += 5;
}
int b = 0;
for(long i = 0;i < count;i++){
b--;
}
long time = System.currentTimeMillis() - start;
System.out.println("serial : " + time + "ms,b = " + b + ",a = " + a);
}
我们来看一些执行结果:
当count = 10000时 输出:concurrency : 1ms,b = -10000 serial : 0ms,b = -10000,a = 50000
当count = 100000时 输出:concurrency : 2ms,b = -100000 serial : 3ms,b = -100000,a = 500000
当count = 1000000时 输出:concurrency : 5ms,b = -1000000 serial : 3ms,b = -1000000,a = 5000000
当count = 10000000时 输出:concurrency : 7ms,b = -10000000 serial : 11ms,b = -10000000,a = 50000000
当count = 100000000时 输出:concurrency : 48ms,b = -100000000 serial : 84ms,b = -100000000,a = 500000000
当运算次数越少的时候,串行执行反而比多线程快,为什么会出现这样的情况?多线程为什么会执行的慢呢?
其实CPU在执行多线程的时候时通过给每个线程分配CPU时间段来实现多线程的,时间片时CPU分配给各个线程的时间,因为时间片非常短(一般在几十毫秒),所以CPU通过不停的切换线程执行,才能让我们感觉到多个线程在同时执行。但是CPU在线程之间的切换前要保留上一个线程的状态,同时加载当前线程的状态,在这个操作过程中也就差生了一定的时间消耗。同时没操作一次,也就完成了一次上下文切换。
如何减少上下文切换?
1、无所并发编程。多线程竞争锁才会引起上下文切换,所以多线程处理数据时可以尽量避免使用锁,如不同线程处理不同段的数据
2、使用最少线程。避免创建不必要的线程,避免大量线程处于等待状态
3、协程。在单线程里面实现多任务调度,并维持多任务之间的切换。