Skip to content

Commit aea67f1

Browse files
authored
Create Print Zero Even Odd.java
1 parent 759dc8e commit aea67f1

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class ZeroEvenOdd {
2+
private int n;
3+
private int flag = 0;
4+
5+
public ZeroEvenOdd(int n) {
6+
this.n = n;
7+
}
8+
9+
// printNumber.accept(x) outputs "x", where x is an integer.
10+
public synchronized void zero(IntConsumer printNumber) throws InterruptedException {
11+
for (int i = 0; i < n; i++) {
12+
while (flag != 0) {
13+
this.wait();
14+
}
15+
printNumber.accept(0);
16+
flag = i % 2 == 0 ? 1 : 2;
17+
this.notifyAll();
18+
}
19+
}
20+
21+
public synchronized void even(IntConsumer printNumber) throws InterruptedException {
22+
for (int i = 2; i <= n; i += 2) {
23+
while (flag != 2) {
24+
this.wait();
25+
}
26+
printNumber.accept(i);
27+
flag = 0;
28+
this.notifyAll();
29+
}
30+
}
31+
32+
public synchronized void odd(IntConsumer printNumber) throws InterruptedException {
33+
for (int i = 1; i <= n; i += 2) {
34+
while (flag != 1) {
35+
this.wait();
36+
}
37+
printNumber.accept(i);
38+
flag = 0;
39+
this.notifyAll();
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)