Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method wait() and notifyAll() is not static

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?

like image 498
user1769712 Avatar asked Feb 19 '26 21:02

user1769712


1 Answers

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
   } 
}
like image 92
John Vint Avatar answered Feb 25 '26 19:02

John Vint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!