Who notifies the Thread when it finishes?

前端 未结 1 1747
星月不相逢
星月不相逢 2020-12-18 13:43

I have one question regarding wait/notify based threads interaction.

The output of the below code is Im. How output can be Im as there is

相关标签:
1条回答
  • 2020-12-18 13:58

    Your program is leaving wait() because the thread is finishing immediately. This is a byproduct of the Thread library that the Thread object is notified when the thread finishes. This is how join() works but it is not behavior that should be relied on since it is internal to the thread sub-system.

    If you are trying to wait for the thread to finish then you should be using the t1.join() method instead.

    Your thread is finishing immediately because it does not have a run() method defined so it is started and finishes. Really it is a race condition and the thread that is started could finish before the main thread gets to the wait() method call. You can see this if you put a short sleep (maybe 10ms) after the start() is called. Then you can see that you program will sit in wait() forever.

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