File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments