public class CompletionServiceDemo {
public static class FutureTaskDemo implements Callable<String>{
private String name;
private Long time;
public FutureTaskDemo(String name, Long time){
this.name = name;
this.time = time;
}
@Override
public String call() {
System.out.printf("子線程 %s 開始: %s \n", name, getDate());
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("子線程 %s 結束: %s \n", name, getDate());
return name;
}
}
public static String getDate(){
Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
return dateFormat.format(date);
}
public static void main(String []args){
System.out.printf("程序開始: %s \n", getDate());
ExecutorService executorService = new ThreadPoolExecutor(5, 5,
1L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);
completionService.submit(new FutureTaskDemo("c0", 2000L));
completionService.submit(new FutureTaskDemo("c1", 1000L));
completionService.submit(new FutureTaskDemo("c2", 4000L));
completionService.submit(new FutureTaskDemo("c3", 5000L));
completionService.submit(new FutureTaskDemo("c4", 3000L));
System.out.printf("開始獲取結果: %s \n", getDate());
for(int i=0; i<5; i++){
System.out.printf("循環(huán)開始 %s, 時間: %s \n", i, getDate());
String result = null;
try {
result = completionService.take().get();
} catch (InterruptedException| ExecutionException e) {
e.printStackTrace();
}
System.out.printf("=====子線程 %s 結束: %s \n", result, getDate());
}
executorService.shutdown();
System.out.printf("程序結束: %s \n", getDate());
}
}
結果如下
程序開始: 2022-05-22 :11:10:25
子線程 c1 開始: 2022-05-22 :11:10:25
子線程 c3 開始: 2022-05-22 :11:10:25
子線程 c2 開始: 2022-05-22 :11:10:25
子線程 c0 開始: 2022-05-22 :11:10:25
開始獲取結果: 2022-05-22 :11:10:25
子線程 c4 開始: 2022-05-22 :11:10:25
循環(huán)開始 0, 時間: 2022-05-22 :11:10:25
子線程 c1 結束: 2022-05-22 :11:10:26
=====子線程 c1 結束: 2022-05-22 :11:10:26
循環(huán)開始 1, 時間: 2022-05-22 :11:10:26
子線程 c0 結束: 2022-05-22 :11:10:27
=====子線程 c0 結束: 2022-05-22 :11:10:27
循環(huán)開始 2, 時間: 2022-05-22 :11:10:27
子線程 c4 結束: 2022-05-22 :11:10:28
=====子線程 c4 結束: 2022-05-22 :11:10:28
循環(huán)開始 3, 時間: 2022-05-22 :11:10:28
子線程 c2 結束: 2022-05-22 :11:10:29
=====子線程 c2 結束: 2022-05-22 :11:10:29
循環(huán)開始 4, 時間: 2022-05-22 :11:10:29
子線程 c3 結束: 2022-05-22 :11:10:30
=====子線程 c3 結束: 2022-05-22 :11:10:30
程序結束: 2022-05-22 :11:10:30