小编amr*_*ita的帖子

等待和通知不是静态的

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

java notify wait

0
推荐指数
1
解决办法
1072
查看次数

标签 统计

java ×1

notify ×1

wait ×1