Join方法的使用,簡單來說就是把指定的線程加入到當前線程,可以將兩個交替執行的線程合併爲順序執行。 比如在線程 B 中調用了線程 A 的 Join()方法,直到線程 A 執行完畢後,纔會繼續執行線程 B。
代碼示例如下所示:
package cn.lspj.ch1.base;
public class UseJoin {
static class A implements Runnable {
private Thread thread;
public A() {
}
public A(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
System.out.println("A 等待執行 ...");
if (thread != null) {
try {
thread.join(); // 線程A中調用了線程B的join方法,需要等待線程B執行完畢後A才能執行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ,A 執行完畢 ...");
}
}
static class B implements Runnable {
@Override
public void run() {
System.out.println("B 等待執行 ...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ,B 執行完畢 ...");
}
}
public static void main(String[] args) throws InterruptedException {
Thread c = Thread.currentThread();
B b = new B();
Thread threadB = new Thread(b); // 線程B
//A a = new A();
A a = new A(threadB);
Thread threadA = new Thread(a); // 線程A
threadA.start();
threadB.start();
System.out.println("C 等待執行 ...");
threadA.join(); // 當前線程C中調用了線程A的join方法,需要等待線程A執行完畢後C才能執行
Thread.sleep(2000); // 主線程休眠2秒
System.out.println(Thread.currentThread().getName() + " ,C 執行完畢 ...");
}
}
代碼執行結果如下:
A 等待執行 ...
C 等待執行 ...
B 等待執行 ...
Thread-0 ,B 執行完畢 ...
Thread-1 ,A 執行完畢 ...
main ,C 執行完畢 ...
從執行結果不難看出,如果當前線程C中調用了線程A的join方法,需要等待線程A執行完畢後C才能執行,線程A中調用了線程B的join方法,需要等待線程B執行完畢後A才能執行。
如果main方法代碼如下,修改爲不適用join方法。
public static void main(String[] args) throws InterruptedException {
Thread c = Thread.currentThread();
B b = new B();
Thread threadB = new Thread(b); // 線程B
A a = new A();
//A a = new A(threadB);
Thread threadA = new Thread(a); // 線程A
threadA.start();
threadB.start();
System.out.println("C 等待執行 ...");
//threadA.join(); // 當前線程C中調用了線程A的join方法,需要等待線程A執行完畢後C才能執行
Thread.sleep(2000); // 主線程休眠2秒
System.out.println(Thread.currentThread().getName() + " ,C 執行完畢 ...");
}
代碼執行結果如下:
C 等待執行 ...
A 等待執行 ...
B 等待執行 ...
main ,C 執行完畢 ...
Thread-1 ,A 執行完畢 ...
Thread-0 ,B 執行完畢 ...
多次運行輸出結果可能還不一樣,因此,如果想要兩個線程按指定順序執行,則使用線程的Join即可。
備註:博主微信公衆號,不定期更新文章,歡迎掃碼關注。