Quantcast
Channel: IT社区推荐资讯 - ITIndex.net
Viewing all articles
Browse latest Browse all 11804

CountDownLatch的使用

$
0
0

        CountDownLatch是一个同步辅助类,犹如倒计时计数器,创建对象时通过构造方法设置初始值,调用CountDownLatch对象的await()方法则处于等待状态,调用countDown()方法就将计数器减1,当计数到达0时,则所有等待者或单个等待者开始执行。

 

public static void main(String[] args) {
	ExecutorService service = Executors.newCachedThreadPool(); //创建一个线程池
	final CountDownLatch cdOrder = new CountDownLatch(1);	//state值为1
	final CountDownLatch cdAnswer = new CountDownLatch(3);	//state值为3
  
	for(int i=0;i<3;i++){
		Runnable runnable = new Runnable(){
			public void run(){
				try {
					System.out.println(""线程"" + Thread.currentThread().getName() + ""正准备接受命令""); 
					cdOrder.await(); //等待直到cdOrder的state值为0时,继续往下执行
					System.out.println(""线程"" + Thread.currentThread().getName() +  ""已接受命令""); 
					TimeUnit.SECONDS.sleep(3);  //线程休眠3秒
					System.out.println(""线程"" + Thread.currentThread().getName() +  ""回应命令处理结果"");   
					cdAnswer.countDown(); //cdAnswer的state值减1
				} catch (Exception e) {
					e.printStackTrace();
				}                
			}
		};
		service.execute(runnable); //为线程池添加任务
	}      
  
	try {
		TimeUnit.SECONDS.sleep(5);  //线程休眠5秒
  
		System.out.println(""线程"" + Thread.currentThread().getName() + ""即将发布命令"");                        
		cdOrder.countDown(); //cdOrder的state值减1

		System.out.println(""线程"" + Thread.currentThread().getName() + ""已发送命令,正在等待结果"");    
		cdAnswer.await(); //等待直到cdAnswer的state值为0时,继续往下执行
		System.out.println(""线程"" + Thread.currentThread().getName() + ""已收到所有响应结果"");    
	} catch (Exception e) {
		e.printStackTrace();
	}                
	service.shutdown(); //任务结束,停止线程池的所有线程
}

 



已有 0人发表留言,猛击->> 这里<<-参与讨论


ITeye推荐




Viewing all articles
Browse latest Browse all 11804

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>