-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCountDownLatchDemo.java
65 lines (60 loc) · 2.14 KB
/
CountDownLatchDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Order 10 threads to first operate the additions and then multiplications on a shared variable using CountDownLatch[1]
* [1] Releases when a count value reaches zero
*/
public class CountDownLatchDemo {
public static int MAX_NUM_THREADS = 10;
public static int sum = 0;
private static final Lock lock = new ReentrantLock();
private static final CountDownLatch barrier = new CountDownLatch(MAX_NUM_THREADS/2);
private static class Counter extends Thread {
private final String name;
Counter(String name) {
this.name = name;
}
public void run() {
if (name.contains("Adder")) {
lock.lock();
try {
sum += 5;
System.out.println("Counter " + name + " changed the value and now is " + sum);
} finally {
lock.unlock();
}
barrier.countDown();
} else { //Multiplier
try {
barrier.await();
} catch (InterruptedException e) { e.printStackTrace(); }
lock.lock();
try {
sum *= 2;
System.out.println("Counter " + name + " changed the value and now is " + sum);
} finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
List<Counter> list = new ArrayList<>();
for (int i = 0; i < MAX_NUM_THREADS / 2 ; i++) {
list.add(new Counter("Adder-" + i));
list.add(new Counter("Multiplier-" + i));
}
for (Counter c : list) {
c.start();
}
for (Counter c : list) {
c.join();
}
System.out.println("Final value and is " + sum);
}
}