CountDownLatch
suggest changeA synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
- A
CountDownLatchis initialized with a given count. - The await methods block until the current count reaches zero due to invocations of the
countDown()method, after which all waiting threads are released and any subsequent invocations of await return immediately. - This is a one-shot phenomenon—the count cannot be reset. If you need a version that resets the count, consider using a
CyclicBarrier.
Key Methods:
public void await() throws InterruptedException
Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.
public void countDown()
Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
Example:
import java.util.concurrent.*;
class DoSomethingInAThread implements Runnable {
CountDownLatch latch;
public DoSomethingInAThread(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
System.out.println("Do some thing");
latch.countDown();
} catch(Exception err) {
err.printStackTrace();
}
}
}
public class CountDownLatchDemo {
public static void main(String[] args) {
try {
int numberOfThreads = 5;
if (args.length < 1) {
System.out.println("Usage: java CountDownLatchDemo numberOfThreads");
return;
}
try {
numberOfThreads = Integer.parseInt(args[0]);
} catch(NumberFormatException ne) {
}
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int n = 0; n < numberOfThreads; n++) {
Thread t = new Thread(new DoSomethingInAThread(latch));
t.start();
}
latch.await();
System.out.println("In Main thread after completion of " + numberOfThreads + " threads");
} catch(Exception err) {
err.printStackTrace();
}
}
}
output:
java CountDownLatchDemo 5
Do some thing
Do some thing
Do some thing
Do some thing
Do some thing
In Main thread after completion of 5 threads
Explanation:
CountDownLatchis initialized with a counter of 5 in Main thread- Main thread is waiting by using
await()method. - Five instances of
DoSomethingInAThreadhave been created. Each instance decremented the counter withcountDown()method. - Once the counter becomes zero, Main thread will resume
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents