1)谁等待这个线程结束
2)等多久
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }
示例:
public static void main(String[] args) { Thread t = new Thread(() -> { System.out.println(1); }); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }
Waits for this thread to die.
this 指的是正在调用 join 方法的引用,即 t
那么便是当前线程(主线程,t的父线程)等待 t 结束
蓝色线代表主线程,绿色线代表子线程,x 轴代表时间条,y轴代表两种运行状态
情形1:子线程运行时间< 父线程等待时间 (父线程多等了一会儿,浪费了点时间)
情形2:子线程运行时间>父线程等待时间 (父线程等的时间不够,子线程还没结束,父线程就着急继续往下进行了)
情形3:子线程运行时间==父线程等待时间 (子线程一结束,父线程就继续往下进行)