java多线程组件一:CountDownLatch使用方法的总结

根据从资料上以及习题时间的总结CountDownLatch 做的事情就是通过对一个计数器的控制,来保证一批动作的执行,且同步性保证个这个计数器的值在多线程之间共享的有效性.

下面有个简单的例子可以说明这点:

public class CountDownLatchDemo {
	public static void main(String[] args) {
		/*
		 * CountDownLatch's parameter will decide whether to print waiting
		 * information 
                  * if parameter >10 will never can't to execute finished information
                  * if parameter==0 , don't need to waiting call working()
		 */
		//in think in java construct parameter is 100, will lead to never print waiting finished information
		CountDownLatch latch = new CountDownLatch(10);
		ExecutorService es = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			es.execute(new WaitingTask(latch));
		}
		for (int i = 0; i < 10; i++) {
			es.execute(new WokingTask(latch));
		}
		es.shutdown();
		System.out.println("Existing");
	}
}

class WokingTask implements Runnable {
	private static int	         count	= 0;
	private int	                 id	   = count++;
	private final CountDownLatch	latch;
	
	public WokingTask(CountDownLatch latch) {
		this.latch = latch;
		
	}
	
	public String toString() {
		return "working:" + id;
	}
	
	public void run() {
		try {
			working();
			latch.countDown();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void working() {
		System.out.println(this + "working");
		try {
			TimeUnit.MILLISECONDS.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class WaitingTask implements Runnable {
	private static int	         count	= 0;
	private int	                 id	   = count++;
	private final CountDownLatch	latch;
	
	public WaitingTask(CountDownLatch latch) {
		this.latch = latch;
	}
	
	public String toString() {
		return "waiting:" + id;
	}
	
	public void run() {
		try {
			latch.await();
			System.out.println(this + " waiting finished....");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值