public class Main {
public static void main(String[] args) {
int taskSize = 5;
ExecutorService executor = Executors.newFixedThreadPool(taskSize);
// 构建完成服务
CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);
for (int i = 1; i <= taskSize; i++) {
// 向线程池提交任务
completionService.submit(new CallableTask(5, i));//返回结果类型FutureTask
}
// 按照完成顺序,打印结果
for (int i = 0; i < taskSize; i++) {
try {
System.out.println("completionService.take().get()" + completionService.take().get());// 阻塞,直到有任务完成可以获取结果
// System.out.println("completionService.take().get()" + completionService.poll());//poll直接返回,不阻塞。但是没有完成的任务则返回null
// System.out.println(completionService.poll(5, TimeUnit.SECONDS));//阻塞等待指定时间,如果有完成结果返回,没有的直接返回null // completionService.submit(new RunnableTask(),2);//completionService提交Runnable任务是无法获取结果的
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
// 所有任务已经完成,关闭线程池
System.out.println("执行完毕....");
executor.shutdown();
}
}
class CallableTask implements Callable<Integer> {
/**
* 休眠时间
*/
private int sleepSeconds;
/**
* 返回的值
*/
private int returnValue;
public CallableTask(int sleepSeconds, int returnValue) {
this.sleepSeconds = sleepSeconds;
this.returnValue = returnValue;
}
@Override
public Integer call() throws Exception {
System.out.println("begin to execute." + this.returnValue);
TimeUnit.SECONDS.sleep(sleepSeconds);
System.out.println("end to execute." + this.returnValue);
return returnValue;
}
}