文章目录
如果一个线程A执行了thread.join()语句,其含义是:当前线程A等待thread线程终止后才从thread.join()返回。线程Thread除了提供join()方法之外,还提供了join(long millis)和join(long millis,int nanos)两个具备超时特性的方法。这两个方法表示,如果线程thread在给定的超时时间里没有终止,那么将会从该超时方法中返回。
例子:
创建10个线程,编号0~9,每个线程调用前一个线程的join()方法,也就是线程0结束了,线程1才能从join()方法中返回,而线程0需要等待main线程结束。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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; } } static class Domino implements Runnable { private Thread thread; Domino(Thread thread) { this .thread = thread; } public void run () { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " terminate." ); } }
1 2 3 4 5 6 7 8 9 10 0 terminate.1 terminate.2 terminate.3 terminate.4 terminate.5 terminate.6 terminate.7 terminate.8 terminate.9 terminate.
从上述输出可以看到,每个线程的终止前提是前驱线程的终止,这里涉及到了等待/通知机制(等待前驱线程结束,接收前驱线程结束通知)。
join()方法的逻辑结构同等待/通知经典范式一致,即加锁,循环和处理逻辑3个部分。