Java多线程--让主线程等待子线程执行完毕

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程--让主线程等待子线程执行完毕相关的知识,希望对你有一定的参考价值。

使用Java多线程编程时经常遇到主线程需要等待子线程执行完成以后才能继续执行,那么接下来介绍一种简单的方式使主线程等待。

java.util.concurrent.CountDownLatch

使用countDownLatch.await()方法非常简单的完成主线程的等待:

public class ThreadWait {

    public static void main(String[] args) throws InterruptedException {
        int threadNumber = 10;
        final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            final int threadID = i;
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(String.format("threadID:[%s] finished!!", threadID));
                    countDownLatch.countDown();
                }
            }.start();
        }

        countDownLatch.await();
        System.out.println("main thread finished!!");
    }
}

以上是关于Java多线程--让主线程等待子线程执行完毕的主要内容,如果未能解决你的问题,请参考以下文章

java主线程等待所有子线程执行完毕在执行(常见面试题)

面试官:如何让主线程等待所有的子线程结束之后再执行?我懵了

多线程《三》join方法

[Java][Android] 多线程同步-主线程等待全部子线程完毕案例

netframework中等待多个子线程执行完毕并计算执行时间

java多线程基本概述——join()方法