Java線程執行順序小結及線程池終止判定__線程池

來源:互聯網
上載者:User
以下有4種測試情況,分別為test1~4.
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import org.junit.Test;public class MyTest {@Testpublic void test1() {// test1:當線程池中所有的線程執行完畢後,才退出主線程.ExecutorService pool = Executors.newCachedThreadPool();for (int i = 0; i < 10; i++) {final int temp = i;pool.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {Thread.sleep(3000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(temp + " finished");}});}pool.shutdown();// 停止加入新的線程while (!pool.isTerminated()) {// 如果所有線程執行完成,那麼挑出該迴圈.}System.out.println("main thread is done");}@Testpublic void test2() {// test2:這種情況比較簡單,先啟動新線程,然後延遲2s,主線程退出.new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("new Thread");}}).start();delay(2000);}@Testpublic void test3() {// test3:這種情況就像麻煩了,如果你的程式子線程中操作時間太長,生命週期比主線程還長,// 那麼主線程結束了,子線程自然也結束了.得不到子線程中想要的結果.// 測試結果:等待2s後,輸出delay is over,並不會輸出new Thread.因為主線程已經結束了.// 如果想保持子線程運行,則需要加入守護線程,或者阻塞主線程,等待子線程完成.new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubdelay(3000);System.out.println("new Thread");}}).start();delay(2000);// 延遲函數}@Testpublic void test4() {// test4:先來說一下輸出結果:1.先輸出delay is over;2.再輸出new Thread.//執行到delay時候,由於主線程被阻塞,所以只能等待delay執行完後才輪到new Threaddelay(2000);// 延遲函數new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("new Thread");}}).start();}private void delay(long ms) {// TODO Auto-generated method stubtry {Thread.sleep(ms);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("delay is over");}}


總結:

1.使用ThreadPool時,先shutDown(不再接受新的線程進入線程池),再通過死迴圈判斷isTerminated(阻塞主線程)  即可判定所有線程是否執行完畢.

2.如果子線程的生命週期比主線程長,應該給子線程加入守護線程,或者阻塞主線程,等待子線程完成(這和Android中的ANR類似..呵呵)

3.切記,不要以為線程在任何地方都是new,start之後就開啟的.就如同上述代碼的test4部分.所以開啟線程時,不要放在不對的位置.



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.