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中的完整資料的時候,這種方法就可以很好的確保兩個線程的同步性。