CompletionService提供了一个线程池执行结果的队列,其中的任务任务执行结果按照任务执行完毕的先后顺序排列放置。示例代码如下:
public class MyTest {
public static void main(String[] args) throws Exception {
ExecutorService executorService = new ThreadPoolExecutor(4,10,10,
TimeUnit.SECONDS,new LinkedBlockingQueue<>(20),
new ThreadPoolExecutor.AbortPolicy());
CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
IntStream.range(0,10).forEach(i -> {
completionService.submit(() -> {
Thread.sleep((long)(Math.random() * 1000));
System.out.println(Thread.currentThread().getName());
return i * i;
});
});
for (int i = 0; i < 10; ++i){
Integer result = completionService.take().get();
System.out.println(result);
}
executorService.shutdown();
}
}