You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

22 lines
878 B

内部通过阻塞队列+FutureTask实现了**任务先完成可优先获取到,即结果按照完成先后顺序排序。**
````java
// 创建线程池
ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);
CompletionService<Integer> cService = new ExecutorCompletionService<>(pool);
// 向里面扔任务
for (int i = 0; i < TOTAL_TASK; i++) {
//这边不是直接通过线程池来提交任务而是通过CompletionService来提交
cService.submit(new WorkTask("ExecTask" + i));
}
// 检查线程池任务执行结果
for (int i = 0; i < TOTAL_TASK; i++) {
//同样也是从CompletionService来取出结果因为CompletionService内部实现通过一个BlockingQueue来保存已经完成的结果。
int sleptTime = cService.take().get();
System.out.println(" slept "+sleptTime+" ms ...");
count.addAndGet(sleptTime);
}
````