等待和通知不是静态的

amr*_*ita 0 java notify wait

wait()和notify()不是静态的,因此编译器应该给出必须从静态上下文调用wait的错误.

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

但是以下代码编译并正常运行.为什么编译器不会在这里给出错误?或者,为什么编译器会在先前的代码中给出必须从静态上下文调用wait的错误?

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();
  }
} 
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 5

您正在调用wait并通知实例方法(public synchronized void run()),根据定义,该方法不是静态的.

  • 如果在main方法中调用wait (静态),则会出现预期的错误.
  • 或者,您可以将方法签名更改为,public static synchronized void run()但是您将获得另一个编译错误,您不再执行Runnable.