0

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();
  }
} 
amrita
  • 133
  • 2
  • 13
  • Not sure where your confusion is, but creating `new World()` in a static method does not make the `new`ed instance somehow static, an instance is an instance. Also adding a static method to your `World` class does not make other methods of that class somehow static. – hyde Jan 17 '13 at 10:50

2 Answers2

5

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.
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    just to add...these methods are methods of Object class, and locking/unlocking the current object when calling directly. You can think of this.wait() etc. In second case World's object will be locked/unlocked. – Amit Jan 17 '13 at 11:07
0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130