CountDownLatch - jdk1.5并发包

什么是CountDownLatch 

CountDownLatch是一种同步类,它运行一个线程在执行前等待一个或多个线程,这经常用于服务器端开发。通常当主线程调用await()方法后将会等待直到计数器到达0或者被其它线程中断。其它线程通过调用countDown()方法将会在完成任务后将计数器减1。计数器为0是主线程将开始运行。

CountDownLatch 例子

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo{
	public static void main(String[] args) {
		final CountDownLatch latch = new CountDownLatch(3);
		Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
       	Thread alertService = new Thread(new Service("AlertService", 1000, latch));
       	Thread validationService = new Thread(new Service("ValidationService", 1000, latch));

       	cacheService.start(); //separate thread will initialize CacheService
       	alertService.start(); //another thread for AlertService initialization
       	validationService.start();

       	try{
       		latch.await();
       		System.out.println("All services are up, Application is starting now");
       	}catch(InterruptedException ie){
       		ie.printStackTrace();
       	}
	}
}

class Service implements Runnable{
    private final String name;
    private final int timeToStart;
    private final CountDownLatch latch;
  
    public Service(String name, int timeToStart, CountDownLatch latch){
        this.name = name;
        this.timeToStart = timeToStart;
        this.latch = latch;
    }
  
    @Override
    public void run() {
        try {
            Thread.sleep(timeToStart);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println( name + " is Up");
        latch.countDown(); //reduce count of CountDownLatch by 1
    }
  
}<strong>
</strong>
output:

AlertService is Up
CacheService is Up
ValidationService is Up
All services are up, Application is starting now

知识点:

1.CountDownLatch 一旦计数器减到0将不能被重用,这是和CyclicBarrier主要的区别

2.主线程调用await()方法等待,其它线程调用countDown()方法来通知主线程已经完成

参考:

http://javarevisited.blogspot.hk/2012/07/countdownlatch-example-in-java.html



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值