Thread Join()的用法

來源:互聯網
上載者:User

Java Thread類有個 join() 方法,先前一直不知道是怎麼用的,直到看到這篇文章。http://auguslee.iteye.com/blog/1292203

Java Thread中, join() 方法主要是讓調用該方法的thread完成run方法裡面的東西後,
再執行join()方法後面的代碼。樣本:

class ThreadTesterA implements Runnable {private int counter;@Overridepublic void run() {while (counter <= 10) {System.out.print("Counter = " + counter + " ");counter++;}System.out.println();}}class ThreadTesterB implements Runnable {private int i;@Overridepublic void run() {while (i <= 10) {System.out.print("i = " + i + " ");i++;}System.out.println();}}public class ThreadTester {public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(new ThreadTesterA());Thread t2 = new Thread(new ThreadTesterB());t1.start();t1.join(); // wait t1 to be finishedt2.start();t2.join(); // in this program, this may be removed}}

t1啟動後,調用join()方法,直到t1的計數任務結束,才輪到t2啟動,然後t2也開始計數任務。可以看到,執行個體中,兩個線程就按著嚴格的順序來執行了。

如果t2的執行需要依賴於t1中的完整資料的時候,這種方法就可以很好的確保兩個線程的同步性。

聯繫我們

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