Java中的CountDownLatch
CountDownLatch的作用:
CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能,当我们创建CountDownLatch的对象时,我们指定了它应等待的线程数,所有此类线程都需要在完成或准备好工作后调用CountDownLatch.countDown()来进行递减计数。一旦计数达到零,等待的任务就会开始运行。
CountDownLatch的示例:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String args[])
throws InterruptedException {
// Let us create task that is going to
// wait for four threads before it starts
CountDownLatch latch = new CountDownLatch(4);
// Let us create four worker
// threads and start them.
Worker first = new Worker(1000, latch,
"WORKER-1");
Worker second = new Worker(2000, latch,
"WORKER-2");
Worker third = new Worker(3000, latch,
"WORKER-3");
Worker fourth = new Worker(4000, latch,
"WORKER-4");
first.start();
second.start();
third.start();
fourth.start();
// The main task waits for four threads
latch.await();
// Main thread has started
System.out.println(Thread.currentThread().getName() +
"has finished");
}
}
// A class to represent threads for which
// the main thread waits.
class Worker extends Thread {
private int delay;
private CountDownLatch latch;
public Worker(int delay, CountDownLatch latch,
String name) {
super(name);
this.delay = delay;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(delay);
latch.countDown();
System.out.println(Thread.currentThread().getName()
+ " finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出:
Output:
WORKER-1 finished
WORKER-2 finished
WORKER-3 finished
WORKER-4 finished
main has finished
CountDownLatch类中最重要的3个方法:
1. public void await() throws InterruptedException { }; //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
2. public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
3. public void countDown() { }; //将count值减1
来源:oschina
链接:https://my.oschina.net/u/4227432/blog/3137408