1.使用CountDownLatch,计数方式判断线程是否结束
定义一个CountDownLatch
private static CountDownLatch cdl = new CountDownLatch(1);//数值是计数器初始值
在主线程中等待,代码如下
try {
cdl.await();
} catch (InterruptedException e) {
}
executorService.shutdown();
在线程池中,执行完线程中的步骤,计数器减一,当计数器得到0,主线程的await就不再等待,主线程被唤醒,写在子线程中的代码如下
cdl.countDown();
然后就可以啦
缺点:不能重复使用,所以…..对于现在的我来说好像没什么用。看别人的博客说,性能貌似也不是很好,不知道为啥,有知道的朋友可以告诉我
2.使用isTerminated判断线程是否结束
前提是在子线程或者线程池里面要把线程或者线程池shutdown
子线程最后加上代码:
executorService.shutdown();//excutorService是线程或者线程池的名字
在主线程中加上代码:
while(true){
if(executorService.isTerminated()){
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
3.使用awaitTermination
和第二个方法类似,只是定下一个时间间隙,让主线程每隔这个时间间隙就去检查子线程是否结束
exec.shutdown();
exec.awaitTermination(1, TimeUnit.HOURS);