通知不起作用.. waitng永远线程Java

use*_*217 1 java multithreading notify wait forever

您好我是编程的新手,我正在尝试做一个简单的生产者 - 消费者问题..但不幸的是我的线程永远等待..notify不工作..任何想法?:/

public synchronized void order() throws Exception{

    System.out.println("User "+name+" requests:\n"+"cherries=" + cherries);

    while(checkValues()==true){
        System.out.println(name+"  waiting");
        wait(); 
    } 
    notify();
    Update();
    store.toString();

    System.out.println(name+" gets resources ");
    Thread.sleep(5000);
 }
Run Code Online (Sandbox Code Playgroud)

Ste*_*n C 5

信不信由你...... wait()notify()工作得很好.

问题是您没有正确使用它们.

while(checkValues()==true){
    System.out.println(name+"  waiting");
    wait(); 
}
notify();
Run Code Online (Sandbox Code Playgroud)

这将等到其他一些线程通知this实例进行方法调用.这不可能是notify();循环之后的调用...'因为在得到通知之前你无法到达那里.

现在有可能其他一些线程可以这样做notify(),但你没有向我们展示那样做的代码.而目前的代码并没有表明这一点.你描述的症状也是如此.


不幸的是,我无法弄清楚你的代码实际上在做什么.这对我来说真的没什么意义.所以我无法建议如何解决它.

我能做的最好的事情是建议您阅读一些使用wait/notify的正确方法的教程示例.例如: