Java Thread join() 的用法

Java Thread中, join() 方法是讓調用該方法的主線程執行run()時暫時卡住,等run()執行完成後, 主線程再調用執行join()後面的代碼。示例:ide

class ThreadTesterA implements Runnable {

	private int counter;

	@Override
	public void run() {
		while (counter <= 10) {
			System.out.print("Counter = " + counter + " ");
			counter++;
		}
		System.out.println();
	}
}

class ThreadTesterB implements Runnable {

	private int i;

	@Override
	public 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 finished
		t2.start();
		t2.join(); // in this program, this may be removed
	}
}

若是去掉t1.join()這個語句事後, 輸出的順序是亂的, 加上這個語句後, 就會按照順序輸出,  從某種意義上說實現了同步。this

相關文章
相關標籤/搜索