最近一個需求需要多線程多文件寫出,寫法是新開了一個固定數量線程池,但是希望主線程能夠得知全部子線程完成後,給瀏覽器返回一個總體線程執行結果。
這裏需要判斷線程池中的線程是否全部執行完畢。
一、方式一:
說明:
pool.isShutDown():當調用shutdown()或shutdownNow()方法後返回爲true。
pool.isTerminated():當調用shutdown()方法後,並且所有提交的任務完成後返回爲true;
pool.isTerminated():當調用shutdownNow()方法後,成功停止後返回爲true;
如果線程池任務正常完成,都爲false
ExecutorService exec = Executors.newCachedThreadPool();
pool.shutdown();
while(true){
if(exec.isTerminated()){
System.out.println("所有的子線程都結束了!");
break;
}
}