在项目实践中经常会遇到一个场景,就是需要等待某几件事情完成后才能继续往下执行,比如多个线程全部加载完毕再汇总处理。
Thread 类中有一个 join 方法可以做这个事情,等待通知方法是 Object 类中的方法,而 join 方法则是 Thread 类直接提供的。join 是无参且返回值为 void 的方法。
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread threadOne = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程one执行完毕。。。");
}
});
Thread threadTwo = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程two执行完毕。。。");
}
});
//启动子线程
threadOne.start();
threadTwo.start();
//等待子线程执行完毕,返回
threadOne.join();
threadTwo.join();
System.out.println("所有子线程执行完毕。。。");
}
}
线程A调用线程B的 join 方法后会被阻塞,当其他线程调用了线程A的 interrupt() 方法中断了线程A时,线程A会抛出 InterruptedException 异常而返回。
public class JoinInterruptTest {
public static void main(String[] args) {
//线程 one
Thread threadOne = new Thread(new Runnable() {
public void run() {
System.out.println("线程 one 开始");
for (;;){
}
}
});
//获取主线程
final Thread mainThread = Thread.currentThread();
//线程 two
Thread threadTwo = new Thread(new Runnable() {
public void run() {
try {
//休眠 1 s
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mainThread.interrupt();
}
});
//启动子线程
threadOne.start();
//延迟 1s 启动线程
threadTwo.start();
try {
threadOne.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}