在java线程创建中,调用 join() 方法可以让当前线程等待目标线程执行完毕后再继续运行。具体做法是获取目标线程对象并调用其 join() 方法,这样主线程或其他调用线程会被阻塞,直到目标线程的 run() 方法结束。如果传入毫秒数作为参数,则最多等待指定时间后无论目标线程是否结束都会恢复执行。

如何确保子线程在主线程之前完成
通过在主线程中调用子线程对象的 join() 方法,可以强制主线程暂停执行,直到该子线程完全终止。这适用于需要收集子线程计算结果或确保资源清理顺序的场景。例如,创建一个负责数据处理的子线程,主线程启动它后立即调用 join(),从而保证后续逻辑只在数据处理完成后才运行。

public class JoinExample {
public static void main(String[] args) throws InterruptedException {
Thread child = new Thread(() -> {
System.out.println("Child thread is running");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("Child thread finished");
});
child.start();
System.out.println("Main thread waiting for child...");
child.join();
System.out.println("Main thread continues after child finishes");
}
}
预期输出顺序为:先打印“Child thread is running”,接着是“Main thread waiting for child...”,然后等待一秒后打印“Child thread finished”,最后打印“Main thread continues after child finishes”。注意 join() 会抛出 InterruptedException,需处理或声明抛出。
join() 带超时参数的行为是什么
当调用 join(long millis) 时,主线程最多等待指定毫秒数。若在此期间子线程结束,主线程立即恢复;若超时后子线程仍未结束,主线程也会继续执行,不再等待。这种机制避免了无限期阻塞,适合对实时性有要求的场景。例如设置超时时间为500毫秒,而子线程实际耗时2秒,则主线程会在500毫秒后继续运行,此时子线程仍在后台执行。

public class JoinTimeoutExample {
public static void main(String[] args) throws InterruptedException {
Thread child = new Thread(() -> {
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("Child thread finished after 2s");
});
child.start();
long start = System.currentTimeMillis();
child.join(500);
long elapsed = System.currentTimeMillis() - start;
System.out.println("Main thread resumed after " + elapsed + "ms");
child.join(); // 可选:最终确认子线程结束
}
}
上述代码中,主线程调用 join(500) 后最多等待500毫秒。由于子线程需2秒才结束,主线程将在约500毫秒后打印“Main thread resumed after ~500ms”,随后子线程在2秒时打印自身结束信息。若后续调用无参 join(),主线程将再次阻塞直至子线程真正结束,确保程序退出前所有线程已完成。
join() 被中断时会发生什么
如果在主线程等待子线程 join() 的过程中,主线程自身被其他线程中断(即调用了 Thread.interrupt()),那么 join() 方法会立即抛出 InterruptedException,主线程的中断状态也会被清除。这意味着等待过程被强行打断,程序必须显式处理该异常,否则可能跳过关键同步逻辑。例如,若在 child.join() 期间调用 Thread.currentThread().interrupt(),则 join() 不会等待子线程结束,而是直接跳转至异常捕获块。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











