等待线程终止

47 阅读1分钟

Thread类的实例方法join

main线程调用t1.join(),main线程阻塞,可通过调用main.interrupt()方法唤醒阻塞线程

Thread t1 = new Thread(()->{
    System.out.println("t1 begin run");
    while (true) {}
});

final Thread mainThread = Thread.currentThread();

Thread t2 = new Thread(()->{
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //中断main线程
    mainThread.interrupt();
});

t1.start();
t2.start();
try {
    t1.join();
} catch (InterruptedException e) {
    System.out.println("main thread:" + e);
}

结果分析:t1线程还一直在运行,main线程中断后返回
t1 begin run
main thread:java.lang.InterruptedException

并发工具类CountDownLatch

应用场景

  1. 等待某几个事情完成后才能继续往下执行。比如多个线程加载资源,需要等待多个线程全部执行完毕再汇总处理。