`
v5browser
  • 浏览: 1140502 次
社区版块
存档分类
最新评论

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

 
阅读更多
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() + "个子线程未执行");
		}

		
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics