1. 程式人生 > 其它 >java 非同步 多執行緒

java 非同步 多執行緒


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";

}