Pergunta

Hello I am new to programming and I am trying to do a simple Producer-Consumer problem..but unfortunately my thread waits forever..notify doesnt work..any ideas? :/

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);
 }
Foi útil?

Solução

Believe it or not ... wait() and notify() work just fine.

The problem is that you are not using them correctly.

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

This is going to wait until some other thread notifies the this instance for the method call. That cannot be the notify(); call after the loop ...'cos you cannot get there until you've been notified.

Now it is possible that some other thread could be doing that notify(), but you haven't shown us the code that does that. And the current code doesn't indicate that. And the symptoms you describe point that way too.


Unfortunately, I cannot figure out what your code is actually trying to do. It really doesn't make much sense to me. So I can't suggest how to fix it.

The best I can do is suggest that you read some tutorial examples of the right way to use wait/notify. For instance:

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top