Method wait() and notifyAll() is not static

user1769712 picture user1769712 · Mar 7, 2013 · Viewed 8.3k times · Source
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;
}

Why the wait() and notifyAll() do no run in this code?

IDE says: the method wait() (or notifyAll) is not static?

Can you help me?

Answer

John Vint picture John Vint · Mar 7, 2013

It is because you are within a static method, which means the method is executing on the class instance and not the object instance. wait and notify are instance methods.

Create an object lock instead and use that to do the synchronization and signaling.

private static final Object lock = new Object();

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