java decrementer_java.util.concurrent.CountDownLatch

java.util.concurrent.CountDownLatch 是一个闭锁实现,它允许一个或多个线程等待一系列指定操作的完成。

CountDownLatch 以一个给定的数量初始化。countDown() 每被调用一次,这一数量就减一。通过调用 await()方法之一,线程可以阻塞等待这一数量到达零。

以下是一个简单示例。Decrementer 三次调用 countDown() 之后,等待中的 Waiter 才会从 await() 调用中释放出来 :

public class CountDownLatchTest {

public static void main(String[] args) throws InterruptedException {

CountDownLatchTest lt = new CountDownLatchTest();

CountDownLatch latch = new CountDownLatch(3);

Waiter waiter = lt.new Waiter(latch);

Decrementer decrementer = lt.new Decrementer(latch);

new Thread(waiter).start();

new Thread(decrementer).start();

}

public class Waiter implements Runnable {

CountDownLatch latch = null;

public Waiter(CountDownLatch latch) {

this.latch = latch;

}

public void run() {

try {

System.out.println("wait for latch count down");

latch.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("Waiter Released");

}

}

public class Decrementer implements Runnable {

CountDownLatch latch = null;

public Decrementer(CountDownLatch latch) {

this.latch = latch;

}

public void run() {

for (int i = 0; i < 3; i++) {

try {

Thread.sleep(1000);

System.out.println("latch count down");

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

this.latch.countDown();//建议将此方法放在finally中执行

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值