public synchronized static int get() {
while(cheia()==false){
try{
wait();
}
catch(InterruptedException e){
}
}
if (fila[inicio] != 0) {
int retornaValor = fila[inicio];
fila[inicio] = 0;
inicio++;
if (inicio == size) {
inicio = 0;
}
notifyAll();
return retornaValor;
}
notifyAll();
return 0;
}
为什么wait()和notifyAll()不在此代码中运行?
IDE说:方法wait()(或notifyAll)不是静态的?
你能帮助我吗?
这是因为您在静态方法中,这意味着该方法正在类实例而不是对象实例上执行。 wait
和notify
是实例方法。
改为创建一个对象锁,并使用它来进行同步和信令。
private static final Object lock = new Object();
public static int get(){
synchronized(lock){
lock.wait();
lock.notify();
...etc
}
}
同步静态方法锁定Class对象,所以你自然可以做到:
[youclass].class.wait();
[youclass].class.notify();
您从静态方法调用非静态方法,如wait()
或notifyAll()
。你不能做这个。将get方法更改为此
public synchronized int get()
你对wait
的期望是什么?你必须等待某个特定的对象被通知,这里没有任何对象。