java.util.concurrent.CountDownLatch是一个并发构造,它允许多个线程等候特定的操作完成。
CountDownLatch用一个数字初始化,通过调用countDown()方法来减低这个值。当一个线程调用await()方法后,它必须等候数值变成0以后才能往后继续执行。
调用await()方法会阻塞线程,直到这个数值变为0.
代码例子:
package com.dufeng.testjava.countdownlatch; import java.util.concurrent.CountDownLatch; public class TestCountDownLatch { public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(3); Waiter waiter = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch); new Thread(waiter).start();
new Thread(decrementer).start(); System.out.println("end");
} }
package com.dufeng.testjava.countdownlatch; import java.util.concurrent.CountDownLatch; public class Waiter implements Runnable { private CountDownLatch latch; public Waiter(CountDownLatch latch) {
this.latch = latch;
} @Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} System.out.println("Waiter Released");
}
}
package com.dufeng.testjava.countdownlatch; import java.util.concurrent.CountDownLatch; public class Decrementer implements Runnable { private CountDownLatch latch; public Decrementer(CountDownLatch latch) {
this.latch = latch;
} @Override
public void run() {
try {
Thread.sleep(1000);
latch.countDown();
System.out.println(latch.getCount()); Thread.sleep(1000);
latch.countDown();
System.out.println(latch.getCount()); Thread.sleep(1000);
latch.countDown();
System.out.println(latch.getCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
执行结果:
end
2
1
0
Waiter Released