Does Java notify waiting threads implicitly?

后端 未结 2 484
野趣味
野趣味 2020-12-11 04:48

I wrote a test app that should never stop. It issues t.wait() (t is a Thread object), but I never call notify. Why does this code end?

相关标签:
2条回答
  • 2020-12-11 05:25

    You're waiting on a Thread - and while most objects aren't implicitly notified, a Thread object is notified when the thread terminates. It's documented somewhere (I'm looking for it...) that you should not use wait/notify on Thread objects, as that's done internally.

    This is a good example of why it's best practice to use a "private" object for synchronization (and wait/notify) - something which only your code knows about. I usually use something like:

    private final Object lock = new Object();
    

    (In general, however, it's cleaner to use some of the higher-level abstractions provided by java.util.concurrent if you can. As noted in comments, it's also a good idea to implement Runnable rather than extending Thread yourself.)

    0 讨论(0)
  • 2020-12-11 05:29

    The JavaDoc for wait gives the answer: spurious wakeups are possible. This means the JVM is free to end a call to wait whenever it wants.

    The documentation even gives you a solution if you don't want this (which is probably always the case): put the call to wait in a loop and check whether the condition you wait for has become true after every wakeup.

    0 讨论(0)
提交回复
热议问题