Pergunta

Great thanks in advance!

I had problems with synchronizing 2 threads: main and thread which is called from StepRunner.java. I just need this that result of the iteration is displayed before a start of the next iteration.

What I want:

Please enter step number [1, 2, 3 or 4] or 5 for exit: 2
Please enter natural value for factorial computing: 2
2! = 2
Please enter step number [1, 2, 3 or 4] or 5 for exit:

What I don't want:

Please enter step number [1, 2, 3 or 4] or 5 for exit: 2
Please enter natural value for factorial computing: 2
Please enter step number [1, 2, 3 or 4] or 5 for exit: 2! = 2

For it I have synchronized block in StepRunner.java:

public void run() {
        thread.start();
        synchronized (thread) {
            try {
                while (thread.isAlive()) { /**Loop is an Oracle's recommendation*/
                    thread.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

But why method wait() works correctly without method notify() in any place of my code?

Foi útil?

Solução

Thread's javadoc states that Thread.notifyAll() is called internally when thread finishes:

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

As you can see, it's not recommended to use this feature, your code can be rewritten as follows:

thread.start();
try {
    thread.join();    
} catch (InterruptedException e) {
    e.printStackTrace();
}

Given the fact that this statement only appeared in Java 7 javadoc and it's recommended not to use this functionality, it looks like this behavior used to be an implementation detail of Thread class, but people began to rely on it, so that language authors had to document it.

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