一奥吩、作用
現(xiàn)有線程對(duì)象threadB
时捌,在線程 A 中調(diào)用threadB.join()
亏吝,那么當(dāng)線程 B 終止后,方法threadB.join()
才返回裹刮。
活生生地把一個(gè)異步的整成了同步任務(wù)
二音榜、概念
三、使用
10個(gè)線程捧弃,編號(hào)0-9赠叼,讓這10個(gè)線程按照編號(hào)順序執(zhí)行
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread previous = Thread.currentThread();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Domino(previous),String.valueOf(i));
thread.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName()+" terminate.");
}
static class Domino implements Runnable {
private Thread mThread;
public Domino(Thread thread) {
mThread = thread;
}
@Override
public void run() {
try {
mThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" terminate.");
}
}
}