首页 > 编程语言 > 详细

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

时间:2016-09-24 13:40:58      阅读:183      评论:0      收藏:0      [点我收藏+]

使用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多线程--让主线程等待子线程执行完毕

原文:http://www.cnblogs.com/eoss/p/5902939.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!