西施越溪女,明艳光云海
最近用线程池和不用线程池做了个速度的测试,在这里备注下:
结果是速度不相上下;
public static void main(String[] args) throws Exception {
notPool();//非线程池
pool();//线程池
}
public static void notPool() {
Long start = System.currentTimeMillis();
final CountDownLatch latch = new CountDownLatch(80); //计数器类
for (int i = 0; i < 80; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
latch.countDown(); //减少锁存器的计数,如果计数达到零,则释放所有等待线程。
}
}).start();
}
try {
latch.await(); //使当前线程等待,知道latch计数为0
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("耗时:" + (System.currentTimeMillis() - start) / 1000 + "秒");
}
public static void pool() {
Long start = System.currentTimeMillis();
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 100, 200, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(5));
for (int j = 0; j < 80; j++) {
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程名:" + Thread.currentThread().getName());
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
}
});
}
executor.shutdown(); //不会立即终止线程池,而是要等所有任务缓存队列中的任务都执行完后才终止,但再也不会接受新的任务
while (true) {
if (executor.isTerminated()) { //如果关闭后所有任务都已完成,则返回 true。注意,除非首先调用 shutdown 或 shutdownNow,否则 isTerminated 永不为 true。
System.out.println("耗时:" + (System.currentTimeMillis() - start) / 1000 + "秒");
break;
}
}
}
关于CountDownLatch类的理解,可以看看这篇:CountDownLatch的简单理解