码迷,mamicode.com
首页 > 编程语言 > 详细

多线程学习7--CountDownLatch

时间:2015-02-08 19:22:03      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

CountDownLatch 倒计时器效果,线程在await处停下,当countDown

为0时就通行

下面模拟一生令下,三条线程开始执行,等三条线程都执行完之后,然后在进行下一阶段操作

package com.condition;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {
	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newCachedThreadPool();
		final CountDownLatch cdOrder = new CountDownLatch(1);
		final CountDownLatch cdCountDown = new CountDownLatch(3);
		for(int i = 0;i < 3;i++){
			Runnable runnable = new Runnable(){
				    @Override
					public void run() {
				    	System.out.println(Thread.currentThread().getName()
								+" 准备接受命令 ");
				    	try {
							cdOrder.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				    	System.out.println(Thread.currentThread().getName()
								+" 正在执行命令 ");
				    	try {
							Thread.sleep((long) (Math.random()*1000));
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				    	System.out.println(Thread.currentThread().getName()
								+" 正在回应 ");
				    	cdCountDown.countDown();
				    }
			};
			 threadPool.execute(runnable);
		}	
		try {
			Thread.sleep((long) (Math.random()*1000));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		synchronized(threadPool){
			System.out.println(Thread.currentThread().getName()
					+" 即将发布命令 ");
			cdOrder.countDown();
			System.out.println(Thread.currentThread().getName()
					+" 正在发布命令 ");
		}
		try {
			cdCountDown.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()
				+" 收到所有结果 ");
	}

}

  

多线程学习7--CountDownLatch

标签:

原文地址:http://www.cnblogs.com/hzmbbbb/p/4280300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!