企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> ### `thread.join()` * 如果一个线程A执行了`thread.join()`语句,其含义是:当前线程A等待`thread`线程终止之后才从`thread.join()`返回。线程Thread除了提供`join()`方法之外,还提供了`join(long millis)`和`join(longmillis,int nanos)`两个具备超时特性的方法。这两个超时方法表示,如果线程thread在给定的超时时间里没有终止,那么将会从该超时方法中返回。 ``` public class JoinDemo { public static void main(String[] args) { 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; } try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " terminate."); } static class Domino implements Runnable{ private Thread thread; public Domino(Thread thread){ this.thread = thread; } public void run(){ try{ thread.join(); }catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " terminate."); } } } ``` <br/> > ### `Thread.join()`源码 当线程终止时,会调用线程自身的`notifyAll()`方法,会通知所有等待在该线程对象上的线程, ``` // 加锁当前线程对象 public final synchronized void join() throws InterruptedException { // 条件不满足,继续等待 while (isAlive()) { wait(0); } // 条件符合,方法返回 } ```