本文主要是介绍ExecutorService为创建的线程池ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
ExecutorService就是要创建的线程池 JAVA中线程池用类ExecutorService代表
,案例ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE)
底层都是通过ThreadPoolExecutor实现的
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}
http://www.mamicode.com/info-detail-2577910.html
案例
// 方法一,自己写集合来实现获取线程池中任务的返回结果
public void testByQueue() throws Exception {
long start = System.currentTimeMillis();
AtomicInteger count = new AtomicInteger(0);
// 创建线程池
ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);
//队列,拿任务的执行结果
BlockingQueue<Future<Integer>> queue =
new LinkedBlockingQueue<>();
// 向里面扔任务
for (int i = 0; i < TOTAL_TASK; i++) {
Future<Integer> future = pool.submit(new WorkTask("ExecTask" + i));
queue.add(future);
}
// 检查线程池任务执行结果
for (int i = 0; i < TOTAL_TASK; i++) {
int sleptTime = queue.take().get();
//System.out.println(" slept "+sleptTime+" ms ...");
count.addAndGet(sleptTime);
}
// 关闭线程池
pool.shutdown();
System.out.println("-------------tasks sleep time "+count.get()
+"ms,and spend time "
+(System.currentTimeMillis()-start)+" ms");
}
其中WorkTask实现了接口Callable
public class WorkTask implements Callable<Integer> {
private String name;
public WorkTask(String name) {
this.name = name;
}
@Override
public Integer call() {
int sleepTime = new Random().nextInt(1000);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 返回给调用者的值
return sleepTime;
}
}
这篇关于ExecutorService为创建的线程池ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!