方法wait()和notifyAll()不是静态的

问题描述 投票:2回答:4
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)不是静态的?

你能帮助我吗?

java multithreading wait producer-consumer notify
4个回答
3
投票

这是因为您在静态方法中,这意味着该方法正在类实例而不是对象实例上执行。 waitnotify是实例方法。

改为创建一个对象锁,并使用它来进行同步和信令。

private static final Object lock = new Object();

public static int get(){
   synchronized(lock){
      lock.wait();
      lock.notify();
      ...etc
   } 
}

2
投票

同步静态方法锁定Class对象,所以你自然可以做到:

[youclass].class.wait();
[youclass].class.notify();

1
投票

您从静态方法调用非静态方法,如wait()notifyAll()。你不能做这个。将get方法更改为此

public synchronized int get()

-1
投票

你对wait的期望是什么?你必须等待某个特定的对象被通知,这里没有任何对象。

© www.soinside.com 2019 - 2024. All rights reserved.