EN
Java concurrency - avoid busy wait using CountDownLatch (inter-thread communication)
2
points
In this article we would like to show to to avoid busy wait in java using CountDownLatch.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchExample {
private final CountDownLatch countDownLatch = new CountDownLatch(2);
private void executeTasks() throws InterruptedException {
// Task 1
Thread thread1 = new Thread(() -> {
try {
simulateTask(300);
} finally {
countDownLatch.countDown();
System.out.println(getThreadName() + " - Task 1 done");
}
});
// Task 2
Thread thread2 = new Thread(() -> {
try {
simulateTask(100);
} finally {
countDownLatch.countDown();
System.out.println(getThreadName() + " - Task 2 done");
}
});
thread1.start();
thread2.start();
System.out.println(getThreadName() + " - waiting to be notified 2 times");
// Causes the current thread to wait until the latch has counted down
// to zero, unless the thread is interrupted.
// If the current count is zero then this method returns immediately.
countDownLatch.await();
System.out.println(getThreadName() + " - notified");
}
private String getThreadName() {
return Thread.currentThread().getName();
}
private void simulateTask(int timeout) {
sleep(timeout);
}
private void sleep(int timeout) {
try {
TimeUnit.MILLISECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
new CountDownLatchExample().executeTasks();
}
}
Output:
main - waiting to be notified 2 times
Thread-1 - Task 2 done
Thread-0 - Task 1 done
main - notified