1.在线程池 ExecutorService的使用过程中,主线程开启了多个子线程,如果判断所有子线程任务是否完成问题;
方法一:
BusinessHandler b = new BusinessHandler(list);
ExecutorService pool = Executors.newFixedThreadPool(340);
for(int i = 0;i<340;i++){
pool.execute(new ThreadCreat(b));
}
pool.shutdown();
boolean isClose= true;
while(isClose){
Thread.sleep(1000);
if(pool.isTerminated()){
System.out.println("-------------已经结束---------");
isClose= false;
}else{
System.out.println(“--------还未结束-----------------");
}
}
在方法一中,每个子线程要执行10s , pool.shutdown 会在for结束后立刻执行(毫秒级的执行速度)执行之后ExecutorService 处于shutdonw状态,此时ExecutorService不在接受任务任务,而子线程并未结束。下面的 while 循环中 pool.isTerminated() 为真的时候,所有线程执行结束,主线程继续往下走;
方法二:
BusinessHandler b = new BusinessHandler(list);
ExecutorService pool = Executors.newFixedThreadPool(340);
for(int i = 0;i<340;i++){
pool.execute(new ThreadCreat(b));
}
pool.shutdown();
boolean statu= pool.awaitTermination(1, TimeUnit.SECONDS);
while(!statu){
statu= pool.awaitTermination(1, TimeUnit.SECONDS);
Thread.sleep(1000);
System.out.println("-----其实这里输出 ExecutorService 并非 shutdow状态,而是Terminated状态-,子线程未结束---------")}
syso("--------------所有任务已经完成----------------")
}
方法二同样能检测到所有任务是否完成,