private static String execute() throws ExecutionException, InterruptedException {
// 定义线程池
ExecutorService exc = Executors.newFixedThreadPool(20);
// 定义结果集
List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
// 定义任务处理
for (int i=0;i<10;i++) {
// 提交任务
int finalI = i;
Future<Boolean> future = exc.submit(() -> {
Thread.sleep(finalI*10);
System.out.println("任务"+ finalI +"end");
return true;
});
// 将每个线程放入线程集合, 这里如果任何一个线程的执行结果没有回调,线程都会自动堵塞
futures.add(future);
}
// 获取结果集
for (Future<Boolean> task : futures) {
Boolean rst = task.get();
if (rst != null) {
System.out.println(rst);
}
}
return "success";
}