-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBarrier.java
More file actions
58 lines (51 loc) · 1.75 KB
/
Barrier.java
File metadata and controls
58 lines (51 loc) · 1.75 KB
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
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
// Barrier class to be implemented using monitors
public class Barrier {
public enum threadState {arriving, leaving}
int size;
private int allThread; // number of all thread
private boolean stateThread; // states of thread
// current number of thread that arrived at the barrier
private AtomicInteger currentThread = new AtomicInteger(0);
// Constructor
Barrier(int size) {
this.size = size;
this.allThread = size;
this.stateThread = true;
}
// Method to wait until all threads have arrived at the barrier
public synchronized void arriveAndWait( ) {
// Your code here
if (this.stateThread) {
if (this.currentThread.incrementAndGet() == this.allThread) {
this.notifyAll();
this.stateThread = false;
} else {
this.waitForOthers();
}
} else if (!this.stateThread) {
if (this.currentThread.decrementAndGet() == 0) {
this.notifyAll();
} else {
this.waitForOthers();
}
//reuse barrier and set current thread to 0 to start again
this.currentThread.set(0);
this.stateThread = true;
} else {
System.out.println("ERROR:THREAD STATE IS NOT KNOWN");
}
}
// Returns the number of threads using the barrier
public int size( ) {
return size;
}
private synchronized void waitForOthers() {
try {
this.wait();
} catch (InterruptedException var2) {
var2.printStackTrace();
}
}
}