How to use CountDownLatch in Java?
In Java, CountDownLatch is a concurrent utility that allows one or more threads to wait for a set of operations to complete.
The usage method of CountDownLatch is as follows:
- Create a CountDownLatch object specifying the number of operations to wait for. For example, if there are n operations that need to wait to complete, a CountDownLatch object can be created and initialized to n.
- After each operation is completed, call the countDown() method of CountDownLatch to decrease the value of the counter. This signifies that an operation has been completed.
- Call the await() method of CountDownLatch in places where all operations need to be completed. This will cause the calling thread to wait until the counter reaches 0.
- When all operations are completed, the value of the counter will become 0, and the calling thread will be released.
Below is a simple example code demonstrating the usage of CountDownLatch:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int numberOfThreads = 3;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
Thread thread = new Thread(new Worker(latch));
thread.start();
}
latch.await();
System.out.println("All threads have completed their work");
}
static class Worker implements Runnable {
private final CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
// 执行一些操作
System.out.println("Thread " + Thread.currentThread().getId() + " is working");
latch.countDown();
}
}
}
In the example above, a CountDownLatch object is created and set to wait for 3 threads. Next, three worker threads are created using a for loop, with each thread invoking the countDown() method to decrement the counter’s value.
Finally, by calling latch.await() method, the main thread will wait until the counter value reaches 0. When all working threads have finished, the counter value will become 0, allowing the main thread to continue executing and print “All threads have completed their work”.
This is the basic usage of CountDownLatch. By using CountDownLatch, it is easy to achieve waiting for a group of operations to complete.