大家new Thread的方式会创建一个线程,在我们有大量的创建线程的时候这样的方法还会可靠吗?每一次new Thread都会重新创建一个线程,而线程的创建和销毁都需要耗时的。在jdk1.5的concurrent包中有一个Executors,他能使我们创建的线程得到复用,不会频繁的创建和销毁线程。
在网上已经有很多博文介绍了Executors了,我们今天主要是我们使用了Executors和每次new一个Thread的对比。
测试代码:
package com.ys.concurrent.test001;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test001 {
private ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
// private ArrayList<String> queue = new ArrayList<String>();
// private CyclicBarrier barrier = new CyclicBarrier(10000000);
private CountDownLatch latch = new CountDownLatch(100000);
ExecutorService es = Executors.newFixedThreadPool(4);
public static void main(String[] args) {
Test001 test001 = new Test001();
long timeStart = System.currentTimeMillis();
test001.start();
System.out.println(System.currentTimeMillis()-timeStart);
}
public void start(){
for (int i = 0; i < 100000; i++) {
Runnable001 runnable001 = this.new Runnable001(i);
es.submit(runnable001);
// new Thread(runnable001).start();
}
es.shutdown();
try {
//等待latch计数为0
latch.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(queue.size());
}
private class Runnable001 implements Runnable{
private int value;
public Runnable001(int value) {
this.value = value;
}
@Override
public void run() {
try {
// barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
queue.offer(value+"");
latch.countDown();//latch计数减一
}
}
}
首先是使用Executors的情况:运行结果如下:
注释:es.submit(runnable001);放开:new Thread(runnable001).start();得到结果:
可见差距之大,(也不排除我使用的参数值不合理的情况);但是我们如果有大量的需要使用线程的话不妨考虑一下线程池。
版权声明:本文为u014104286原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。