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.
xxxxxxxxxx
1
import java.util.concurrent.CountDownLatch;
2
import java.util.concurrent.TimeUnit;
3
4
public class CountDownLatchExample {
5
6
private final CountDownLatch countDownLatch = new CountDownLatch(2);
7
8
private void executeTasks() throws InterruptedException {
9
10
// Task 1
11
Thread thread1 = new Thread(() -> {
12
try {
13
simulateTask(300);
14
} finally {
15
countDownLatch.countDown();
16
System.out.println(getThreadName() + " - Task 1 done");
17
}
18
});
19
20
// Task 2
21
Thread thread2 = new Thread(() -> {
22
try {
23
simulateTask(100);
24
} finally {
25
countDownLatch.countDown();
26
System.out.println(getThreadName() + " - Task 2 done");
27
}
28
});
29
30
thread1.start();
31
thread2.start();
32
33
System.out.println(getThreadName() + " - waiting to be notified 2 times");
34
35
// Causes the current thread to wait until the latch has counted down
36
// to zero, unless the thread is interrupted.
37
// If the current count is zero then this method returns immediately.
38
countDownLatch.await();
39
System.out.println(getThreadName() + " - notified");
40
}
41
42
private String getThreadName() {
43
return Thread.currentThread().getName();
44
}
45
46
private void simulateTask(int timeout) {
47
sleep(timeout);
48
}
49
50
private void sleep(int timeout) {
51
try {
52
TimeUnit.MILLISECONDS.sleep(timeout);
53
} catch (InterruptedException e) {
54
e.printStackTrace();
55
}
56
}
57
58
public static void main(String[] args) throws InterruptedException {
59
new CountDownLatchExample().executeTasks();
60
}
61
}
Output:
xxxxxxxxxx
1
main - waiting to be notified 2 times
2
Thread-1 - Task 2 done
3
Thread-0 - Task 1 done
4
main - notified