技术的使用都离不开应用场景。多线程是否一定能提高效率,还是要分场景,不能一概而论。以下给出一个例子,功能就是从1加到10亿,我们可以看下单线程和多线程的区别。
这段程序运行在我自己本子上,本子是双核的,但这并不影响实验结果。
代码如下:
package com.java.threads;
/**
* 用于测试多线程适用情况
* 2013-03-09
*/
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ThreadTest extends Thread{
public volatile static long i =0; //初始值0
public static long MAX = 1000000000L;//目标值10亿
private final CountDownLatch start;
private final CountDownLatch end;
ThreadTest(CountDownLatch start,CountDownLatch end){
this.start = start;
this.end = end;
}
@Override
public void run()
{
try {
start.await();//等待开始信号
while(++i< MAX){
}
} catch (InterruptedException e) {//不管
}finally{
end.countDown();//结束就减少一个
}
}
/**
* 当threadNum设置为 1时 ,执行时间: 11145 毫秒
* 当threadNum设置为 2时 ,执行时间: 48991 毫秒
* 当threadNum设置为 4时 ,执行时间: 65624 毫秒
* 当threadNum设置为 8时 ,执行时间: 89904 毫秒
* 当threadNum设置为10时,执行时间:104315 毫秒
*/
public static void main(String[] args) throws Exception {
int threadNum = 1;//线程个数
CountDownLatch start = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(threadNum);
for(int j=0 ;j < threadNum;j++ ){
new ThreadTest(start,end).start();
}
long startTime = System.currentTimeMillis();//开始统计
start.countDown();
end.await();
System.out.print(System.currentTimeMillis()-startTime);//输出最终结果
}
}
我们可以看到,在此种场景下随着线程数增多,计算时间反而下降。线程之间的切换占用了不少时间。所以其实并不是所有的计算密集型用单线程更适合,下面博客中介绍了一个将多线程用于计算密集型的场景:
http://blog.youkuaiyun.com/zhaonanemail/article/details/7175449 在此贴出来以供读者参考。
选择多线程/单线程还是要区分场景,灵活运用。