InterruptedException
- if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.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)); } }
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)); } }
//模拟一个死锁(主线程等待自己死亡之后再死亡,一直会有个等待死亡的线程导致程序进程不能结束) //start httpServer和JettyHttpServer.start()是两个守护线程,会随着主线程死亡而死亡 //要保持其长连接,可以使用主线程的join()方法,保证主线程一直存活,从而使得守护线程也存活 Thread.currentThread().join();
这个方法使main线程一直存活