1. 程式人生 > >執行緒Thread join 方法---優先執行

執行緒Thread join 方法---優先執行

join方法:

當A執行緒執行到了B執行緒的join()方法,A就會等待,等B執行緒都執行完,A才會執行。

join可以用來臨時加入執行緒執行。

class Demo implements Runnable {

	@Override
	public void run() {
		for (int x = 0; x < 70; x++)
			System.out.println(Thread.currentThread().getName() + "=====" + x);
	}

}

/**
 * 情況1 : t1.start(), t1.join() t1.join(),t1搶奪cpu執行權,主執行緒將執行權凍結 t1拿到執行權
 * 直到t1結束後,主執行緒才開始執行
 * 
 * 
 * 情況2: t1.start(); t2.start(); t1.join(); t1搶奪cpu執行權,主執行緒將執行權凍結,
 * t1拿到執行權,直到t1結束後,主執行緒才開始執行 所以:此時能參與搶奪執行權的是t1和t2 知道t1結束,主執行緒加入搶奪
 * 
 * @author qingxiangzhang
 * 
 */
public class JoinDemo {
	public static void main(String[] args) {
		Demo d = new Demo();
		Thread t1 = new Thread(d);
		Thread t2 = new Thread(d);
		try {
			t1.start();
			t2.start();
			t1.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (int x = 0; x < 80; x++)
			System.out.println("main...." + x);
		System.out.println("over");
	}
}