-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintZeroEvenOdd.java
More file actions
49 lines (36 loc) · 1.16 KB
/
PrintZeroEvenOdd.java
File metadata and controls
49 lines (36 loc) · 1.16 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
class ZeroEvenOdd {
private int n;
private volatile int current;
private Semaphore sem1, sem2, sem3;
public ZeroEvenOdd(int n) {
this.n = n;
current = 0;
sem1 = new Semaphore(1);
sem2 = new Semaphore(0);
sem3 = new Semaphore(0);
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
for(int i = 0; i < n; i++) {
sem1.acquire();
printNumber.accept(0);
current++;
if(current % 2 == 0) sem2.release();
else sem3.release();
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for(int i = 2; i <= n; i += 2) {
sem2.acquire();
printNumber.accept(i);
sem1.release();
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for(int i = 1; i <= n; i += 2) {
sem3.acquire();
printNumber.accept(i);
sem1.release();
}
}
}