打印零与奇偶数
class ZeroEvenOdd {
private int n;
private volatile int i = 0;
private volatile int sign = 1;
public ZeroEvenOdd(int n) {
this.n = n;
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
// 上锁
synchronized (this){
while(i < 2 * n){
// 输出
if(i % 4 == 0 || i % 4 == 2){
i += 1;
printNumber.accept(0);
notifyAll();
}else {
// 阻塞
wait();
}
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
// 上锁
synchronized (this){
while(i < 2 * n){
// 输出
if(i % 4 == 3){
printNumber.accept(sign);
sign += 1;
i += 1;
notifyAll();
}else {
// 阻塞
wait();
}
}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
// 上锁
synchronized (this){
while(i < 2 * n){
if(i % 4 == 1){
printNumber.accept(sign);
sign += 1;
i += 1;
notifyAll();
}else {
wait();
}
}
}
}
}