这次不用显示锁了,用个同步代码段吧,其实一样的意思。
class ZeroEvenOdd {
private int n;
private int flag = 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 {
for (int i = 0; i < n; i++) {
synchronized (this) {
while (flag != 0) {
this.wait();
}
printNumber.accept(0);
if(i%2 == 0){
flag = 2;
}else{
flag = 1;
}
this.notifyAll();
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for (int j = 2; j <= n; j = j + 2) {
synchronized (this) {
while (flag != 1) {
this.wait();
}
printNumber.accept(j);
flag = 0;
this.notifyAll();
}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for (int j = 1; j <= n; j = j + 2) {
synchronized (this) {
while (flag != 2) {
this.wait();
}
printNumber.accept(j);
flag = 0;
this.notifyAll();
}
}
}
}