这个问题来自 Leetcode:https ://leetcode.com/problems/print-zero-even-odd/
这是我的代码:
class ZeroEvenOdd {
private int n;
State state;
Type prevState = Type.EVEN;
int count = 1;
public ZeroEvenOdd(int n) {
this.n = n;
state = new State(Type.ZERO);
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
synchronized(state){
while(state.type != Type.ZERO){
state.wait();
}
printNumber.accept(0);
if(prevState == Type.EVEN)
state.type = Type.ODD;
else
state.type = Type.EVEN;
}
state.notifyAll();
}
public void even(IntConsumer printNumber) throws InterruptedException {
synchronized(state){
while(state.type != Type.EVEN){
state.wait();
}
printNumber.accept(count);
count++;
prevState = state.type;
state.type = Type.ZERO;
}
state.notifyAll();
}
public void odd(IntConsumer printNumber) throws InterruptedException {
synchronized(state){
while(state.type != Type.ODD){
state.wait();
}
printNumber.accept(count);
count++;
prevState = state.type;
state.type = Type.ZERO;
}
state.notifyAll();
}
public class State{
public Type type;
public State(Type type){
this.type = type;
}
}
public enum Type {
ZERO, ODD, EVEN
}
}
我们需要打印01020304050
收到以下错误:Thrown exception java.lang.IllegalMonitorStateException
不知道我哪里出错了?我是多线程和并发的新手。有人可以帮忙吗?
谢谢你。