官网描述
join
public final void join() throws InterruptedExceptionWaits for this thread to die.An invocation of this method behaves in exactly the same way as the invocation
join(0)
- Throws:
InterruptedException
- if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
- 等该线程执行完之后再执行后面的业务逻辑
- join(long millis) 最多等该线程多少毫秒就执行后面逻辑
- join(long millis, int nanos)最多等该线程多少纳秒就执行后面的逻辑
代码演示
package com.dwz.concurrency.chapter5; import java.util.Optional; import java.util.stream.IntStream; /** * 在t1线程执行100毫秒,10纳秒之后执行 main主线程相关业务 */ public class ThreadJoin2 { public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { try { System.out.println("t1 is running"); Thread.sleep(10_000); System.out.println("t1 is done"); } catch (InterruptedException e) { e.printStackTrace(); } }); t1.start(); // t1.join();--等t1执行完 t1.join(100, 10);---等t1执行100毫秒,10纳秒之后
Optional.of("All of tasks finish done.").ifPresent(System.out::println); IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "->" + i)); } }
join()在多线程中的使用
package com.dwz.concurrency.chapter5; import java.util.Optional; import java.util.stream.IntStream; /** * join()是在start()之后调用,保证t1、t2执行完毕后再执行main线程业务逻辑 * join()是相对于main线程而言的,t1、t2是同级并发交叉执行的 */ public class ThreadJoin { public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "->" + i)); }); Thread t2 = new Thread(() -> { IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "->" + i)); }); t1.start(); t2.start(); t1.join(); t2.join(); Optional.of("All of tasks finish done.").ifPresent(System.out::println); IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "->" + i)); } }
如果采用如下执行顺序:
t1.start();
t1.join();
t2.start();
t2.join();
结果是t1执行完才会执行t2
main线程的join()
//模拟一个死锁(主线程等待自己死亡之后再死亡,一直会有个等待死亡的线程导致程序进程不能结束) //start httpServer和JettyHttpServer.start()是两个守护线程,会随着主线程死亡而死亡 //要保持其长连接,可以使用主线程的join()方法,保证主线程一直存活,从而使得守护线程也存活 Thread.currentThread().join();
这个方法使main线程一直存活