一、作用
现有线程对象threadB
,在线程 A 中调用threadB.join()
,那么当线程 B 终止后,方法threadB.join()
才返回。
活生生地把一个异步的整成了同步任务
二、概念
三、使用
10个线程,编号0-9,让这10个线程按照编号顺序执行
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.");
}
}
}