Understanding and utilizing CountDownLatch.
CountDownLatch is a concurrency utility class in Java that is used to implement the functionality of thread waiting. It allows one or more threads to wait for the completion of operations by other threads before continuing.
CountDownLatch uses a counter to implement waiting. The initial value of the counter can be set to a positive integer, when a thread completes its task, the value of the counter is decreased by 1. When the counter’s value becomes 0, all waiting threads will be released and can continue execution.
The main methods of CountDownLatch include:
- CountDownLatch(int count): Constructor that sets the initial value of the counter.
- Await(): It makes the current thread wait until the value of the counter becomes zero.
- Decrease the value of the counter by 1 in the countDown function.
Here is an example of using CountDownLatch:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3); // 设置计数器的初始值为3
Worker worker1 = new Worker(latch, "Worker1");
Worker worker2 = new Worker(latch, "Worker2");
Worker worker3 = new Worker(latch, "Worker3");
worker1.start();
worker2.start();
worker3.start();
latch.await(); // 等待所有线程执行完毕
System.out.println("All workers have finished their tasks.");
}
}
class Worker extends Thread {
private CountDownLatch latch;
public Worker(CountDownLatch latch, String name) {
super(name);
this.latch = latch;
}
public void run() {
try {
Thread.sleep(1000); // 模拟任务执行时间
System.out.println(getName() + " has finished its task.");
latch.countDown(); // 计数器的值减1
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In the example above, we created a CountDownLatch object with an initial value of 3. Three Worker threads were then created and assigned tasks. After each Worker thread completes its task, it calls the countDown() method to decrement the counter value. The main thread calls the await() method to wait for the counter value to reach 0, meaning all Worker threads have completed their tasks before the main thread can continue execution.
Please note that the counter of CountDownLatch is one-time use only, once the counter value reaches 0, it cannot be reset to another value. If you need to use the counter multiple times, consider using the CyclicBarrier class.