Java 如何判斷線程池所有任務是否執行完畢

來源:互聯網
上載者:User

標籤:線程池   java   線程   

shutdown
void shutdown()
啟動一次順序關閉,執行以前提交的任務,但不接受新任務。如果已經關閉,則調用沒有其他作用。

拋出:
SecurityException - 如果安全管理器存在並且關閉,此 ExecutorService 可能操作某些不允許調用者修改的線程(因為它沒有保持 RuntimePermission("modifyThread")),或者安全管理器的 checkAccess 方法拒絕訪問。

isTerminated
boolean isTerminated()
如果關閉後所有任務都已完成,則返回 true。注意,除非首先調用 shutdown 或 shutdownNow,否則 isTerminated 永不為 true。

返回:
如果關閉後所有任務都已完成,則返回 true




/**

 * 採用線程池開啟多個子線程,主線程等待所有的子線程執行完畢 */public static void moreThread() {try {int threadNum = 0;for (int i = 0; i < 10; i++) {threadNum++;final int currentThreadNum = threadNum;exe.execute(new Runnable() {@Overridepublic void run() {try {System.out.println("子線程[" + currentThreadNum + "]開啟");Thread.sleep(1000*10);} catch (InterruptedException e) {e.printStackTrace();}finally{System.out.println("子線程[" + currentThreadNum + "]結束");}}});  }System.out.println("已經開啟所有的子線程");exe.shutdown();System.out.println("shutdown():啟動一次順序關閉,執行以前提交的任務,但不接受新任務。");while(true){if(exe.isTerminated()){System.out.println("所有的子線程都結束了!");break;}Thread.sleep(1000);  }} catch (InterruptedException e) {e.printStackTrace();}finally{System.out.println("主線程結束");}}


子線程[1]開啟子線程[6]開啟子線程[2]開啟子線程[5]開啟子線程[9]開啟已經開啟所有的子線程子線程[3]開啟子線程[7]開啟子線程[10]開啟shutdown():啟動一次順序關閉,執行以前提交的任務,但不接受新任務。子線程[4]開啟子線程[8]開啟子線程[6]結束子線程[3]結束子線程[7]結束子線程[2]結束子線程[1]結束子線程[5]結束子線程[9]結束子線程[4]結束子線程[10]結束子線程[8]結束所有的子線程都結束了!主線程結束



借鑒文章地址:

http://blog.csdn.net/truong/article/details/40227435 原文地址




Java 如何判斷線程池所有任務是否執行完畢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.