-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZeroEvenOdd.java
More file actions
112 lines (101 loc) · 3.35 KB
/
ZeroEvenOdd.java
File metadata and controls
112 lines (101 loc) · 3.35 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.leetcode.thread;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;
class ZeroEvenOdd {
private int n;
private Lock lock = new ReentrantLock();
private Condition zero=lock.newCondition();
private Condition even=lock.newCondition();
private Condition odd=lock.newCondition();
private volatile AtomicInteger seqs = new AtomicInteger(0);
private volatile int status=0;
public ZeroEvenOdd(int n) {
this.n=n;
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
lock.lock();
while (status!=0)
zero.await();
printNumber.accept(0);
int val = seqs.incrementAndGet();
if((val&1)==1) {
even.signal();
status=1;
}else {
odd.signal();
status=2;
}
lock.unlock();
}
public void even(IntConsumer printNumber) throws InterruptedException {
lock.lock();
while (status!=1)
even.await();
printNumber.accept(seqs.get());
zero.signal();
status=0;
lock.unlock();
}
public void odd(IntConsumer printNumber) throws InterruptedException {
lock.lock();
while (status!=2)
odd.await();
printNumber.accept(seqs.get());
zero.signal();
status=0;
lock.unlock();
}
public static void main(String[] args) {
// Integer n =Integer.parseInt(args[0]);
Integer n =4;
ZeroEvenOdd zeo = new ZeroEvenOdd(n);
IntConsumer consumer = new IntConsumer() {
@Override
public void accept(int value) {
System.out.print(value);
}
};
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= n; i++) {
try {
zeo.zero(consumer);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int loops = ((n & 1) == 1) ? n / 2 + 1 : n / 2;
for (int i = 1; i <= loops; i++) {
try {
zeo.even(consumer);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int loops = n / 2;
for (int i = 1; i <= loops; i++) {
try {
zeo.odd(consumer);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}