-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCyclicBarrier
59 lines (43 loc) · 1.18 KB
/
CyclicBarrier
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
package soccer.play;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
public class Task implements Runnable{
private int id;
private CyclicBarrier barrier;
private Random random;
public Task(int id, CyclicBarrier barrier) {
this.id=id;
this.barrier=barrier;
this.random=new Random();
}
@Override
public void run() {
System.out.println("Task with id "+id+" has started....");
try {
Thread.sleep(random.nextInt(3000));
System.out.println("Barried reached for thread with id "+id);
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class League {
public static void main(String[] args) {
ExecutorService executor=Executors.newFixedThreadPool(5);
CyclicBarrier cb=new CyclicBarrier(5,new Runnable(){
@Override
public void run() {
System.out.println("All threads reached the barrier");
}
});
for(int i=0;i<10;i++) {
executor.execute(new Task(i+1,cb));
}
executor.shutdown();
}
}