amrita
amrita

Reputation: 133

wait and notify are not static

wait() and notify() are not static, so the compiler should give error that wait must be called from static context.

public class Rolls {
  public static void main(String args[]) {
    synchronized(args) {
        try {
            wait();
        } catch(InterruptedException e)
        { System.out.println(e); }
    }
  }
}

But the following code compiles and runs properly. Why does compiler not give errors here? Alternatively, why does the compiler give the error in the previous code that wait must be called from a static context?

public class World implements Runnable {
  public synchronized void run() {
    if(Thread.currentThread().getName().equals("F")) {
        try {
            System.out.println("waiting");
            wait();
            System.out.println("done");
        } catch(InterruptedException e) 
        { System.out.println(e); }
    }
    else {
        System.out.println("other");
        notify();
        System.out.println("notified");
    }
  }
  public static void main(String []args){
    System.out.println("Hello World");
    World w = new World();
    Thread t1 = new Thread(w, "F");
    Thread t2 = new Thread(w);
    t1.start();
    t2.start();
  }
} 

Upvotes: 0

Views: 1144

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533710

when does the compiler give the error that wait must be called from a static contex

The error message is that the method must NOT be called from a static context. If you try to use it in a static method without an instance you will get this error.

Upvotes: 0

assylias
assylias

Reputation: 328735

You are calling wait and notify from an instance method (public synchronized void run()), which by definition is not static.

  • If you call wait within the main method, which is static, you will get the error you expect.
  • Alternatively, you can change the method signature to public static synchronized void run() but you will get another compile error as well, that you are not implementing Runnable any more.

Upvotes: 5

Related Questions