主线程等待所有子线程执行完毕例子

来源:互联网 发布:怎么查看淘宝客的佣金 编辑:程序博客网 时间:2024/03/29 03:50
import java.util.concurrent.CountDownLatch;public class RRR {public static void main(String[] args) throws InterruptedException {int threadNumber = 10;for(int j =0;j<=2;j++){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((long) (Math.random() * 10000));} 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!!");System.out.println("还剩下"+countDownLatch.getCount() + "个子线程未执行");}}}