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

编程爱好者联盟 2016-09-24

使用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!!");
    }
}

相关推荐