-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathUsingBarriers.java
46 lines (37 loc) · 1.28 KB
/
UsingBarriers.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
package br.com.leonardoz.features.synchronizers;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executors;
/**
* Barriers are used for blocking a group of threads until they come together at
* a single point in order to proceed. Basically, convergence of threads.
*
* Accepts a runnable in it's constructor to be called when the threads reach the
* barrier, but before its unblocked
*
* Most common implementation is cyclic barrier.
*
*/
public class UsingBarriers {
public static void main(String[] args) {
Runnable barrierAction = () -> System.out.println("Well done, guys!");
var executor = Executors.newCachedThreadPool();
var barrier = new CyclicBarrier(10, barrierAction);
Runnable task = () -> {
try {
// simulating a task that can take at most 1sec to run
System.out.println("Doing task for " + Thread.currentThread().getName());
Thread.sleep(new Random().nextInt(10) * 100);
System.out.println("Done for " + Thread.currentThread().getName());
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
};
for (int i = 0; i < 10; i++) {
executor.execute(task);
}
executor.shutdown();
}
}