如何判断线程运行结束
2019獨角獸企業重金招聘Python工程師標準>>>
1.join()
????如果是一個線程,可以使用此方法,多個不合適
2.CountDownLatch
????此為并發計數器,每個線程結束后減一(countDown()),countDownLatch.await();//等待所有子線程執行完
3.線程池ThreadPoolExecutor的shutdown與awaitTermination方法
????executor.shutdown();//只是不能再提交新任務,等待執行的任務不受影響 ?
????try { ?
? ? ? ? ? ? boolean loop = true; ?
? ? ? ? ? ? do { ? ?//等待所有任務完成 ?
? ? ? ? ? ? ? ? loop = !executor.awaitTermination(2, TimeUnit.SECONDS); ?//阻塞,直到線程池里所有任務結束
? ? ? ? ? ? } while(loop); ?
? ? ? ? } catch (InterruptedException e) { ?
? ? ? ? ? ? e.printStackTrace(); ?
? ? ? ? } ?
????
????service.shutdown();??
????while(!service.awaitTermination(2,?TimeUnit.SECONDS)){??
????????????System.out.println("service?not?stop");?
? ? ? ? }??
? ?
????//或者isTerminated,如果關閉后所有任務都已完成,則返回?true。注意,除非首先調用?shutdown?或?shutdownNow,否則?isTerminated?永不為?true。
????executor.shutdown();//只是不能再提交新任務,等待執行的任務不受影響 ?
????while(true){ ?
? ? ? ? ? ? if(exe.isTerminated()){?
? ? ? ? ? ? ? ? System.out.println("所有的子線程都結束了!"); ?
? ? ? ? ? ? ? ? break; ?
? ? ? ? ? ? } ?
? ? ? ? ? ? Thread.sleep(1000); ? ?
? ? ? ? } ?
?
?
ThreadPoolExecutor.getActiveCount()?==?0? ??
轉載于:https://my.oschina.net/u/3705388/blog/1828301
總結
以上是生活随笔為你收集整理的如何判断线程运行结束的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iframe子页面与父页面元素的访问以及
- 下一篇: 你真的会使用Glide吗?——Glide