为什么 MainClass 没有从等待状态中出来

Why MainClass is not coming out from waiting state

在下面的代码中,为什么 wait() 之后的部分不会执行。 即使主线程拥有锁的对象中有 notify()。

public class MainClass {

    public static void main(String[] args) {
        Demo dm = new Demo();
        dm.add();

        synchronized (dm) {
            try {
                System.out.println("going to wait");
                dm.wait();
                System.out.println("after wait");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(dm.result);              
        }
    }
}

class Demo  {
    int result;

    public void add(){
        System.out.println("in demo");
        synchronized (this) {
            System.out.println("in demo syn block");
            for(int i=0;i<=10;i++) {
                result=i+result;                
            }
            System.out.println("IN demo:"+result);
            notify();       
            }
        }
    }
}

我需要知道的是 - 为什么 wait() 之后的代码不执行,即使 notify() 是 there.If 我尝试使用线程解决这个问题,然后 wait() 退出它的状态自动。

您调用的顺序有误

  1. 首先,您从 main 线程调用 Demo class 的 dm.add(); 方法。
  2. 此方法将获取 Demo 对象的锁并执行任务并完成。
  3. 然后你在主线程中获取 dm 对象的锁并开始等待它。

所以这里发生的是你在等待,然后没有人通知。所以你的代码永远不会执行写在 wait 语句

之后