多线程一定比单线程快吗?
我们知道,使用多线程,可以同时执行多个任务,从表面上看,多线程明显是要快于单线程的。但是,多线程的创建,上下文的切换也是需要开销的,所以多线程不一定比单线程快,接下来我们来看一个简单的测试用例。
该测试用例分别使用单线程和多线程进行 a 的递增,b 的递减操作,我们通过控制循环次数,来比较相同次数下,串行和并行所花时间。
public class TimeTest {
public final int count = 1000000;
public static void main(String[] args) throws InterruptedException {
TimeTest timeTest = new TimeTest();
System.out.println("执行 " + timeTest.count + " 次");
timeTest.serial(); //串行
timeTest.parallel(); //并行
}
public void serial() {
int a = 0;
int b = 0;
long l = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
a++;
}
for (int i = 0; i < count; i++) {
b--;
}
System.out.println("串行----->" + (System.currentTimeMillis() - l));
}
public void parallel() throws InterruptedException {
int b = 0;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int a = 0;
for (int i = 0; i < count; i++) {
a++;
}
}
});
long l = System.currentTimeMillis();
thread.start();
for (int i = 0; i < count; i++) {
b--;
}
thread.join(); //等thread线程执行完毕再输出时间差
System.out.println("并行----->" + (System.currentTimeMillis() - l));
}
}
输出结果:
count | 100 | 10000 | 100000 | 500000 | 1000000 |
---|---|---|---|---|---|
单线程(ms) | 0 | 0 | 2 | 2 | 4 |
多线程 (ms) | 0 | 0 | 2 | 3 | 2 |
由上表可以发现,执行次数在 50w 次左右,单线程比多线程快,100w 左右,多线程比单线程快,所以,多线程不一定比单线程快。
注:以上测试结果对比可能不太明显,计算时间差时可以使用 System.nanoTime(),单位精确到纳秒级。