很多时候,一个线程的输入可能非常依赖于另外一个或者多个线程的输出,此时,这个线程就需要等待依赖的线程执行完毕,才能继续执行。Thread类提供了join方法来实现这个功能。Thread类对join方法提供了几种不同的重载版本,我们重点关心以下两种:
public final void join() throws InterruptedException
public final synchronized void join(long millis)
throws InterruptedException
方法一表示无限等待,直到目标线程执行结束或者当前线程被中断(调用interrupt()方法);方法二表示有限时长的等待要么目标线程执行结束唤醒当前线程,要么等待时间截至或者被中断。
join方法的使用:假如线程一需要等待线程二执行结束,那么就在线程一中调用线程二的join()方法,如下代码所示:
代码1
public class JoinTest {
public static void main(String[] args) throws InterruptedException{
MyThread thread = new MyThread();
thread.start();
thread.join();
System.out.println(thread.num);