问题
I wanted to start a computation and terminate it on user Cancel. You say that calling Thead.stop()
unlocks all monitors and raises ThreadDeath
exception. This means that finally
is still called.
Suppose I do not care about the locks but want to release the resources allocated so far. I would like the canceller to know/wait until thread has finished released its allocations. Suppose the finally section has an infinite loop in the finally section. Will thread.join
succeed to that thread?
回答1:
It depends on what code the thread is executing at the point where ThreadDeath is thrown. For instance, if your thread is stopped just as it happens to reach the top of a finally block, then you could have a situation where ThreadDeath is thrown after the block is entered but before the resource is closed, and that finally block would not be completed.
It would be a lot less error-prone to use interruption, which lets the thread being interrupted have full control over how it finishes up and closes its resources.
来源:https://stackoverflow.com/questions/37195300/thread-lifecycle-on-threaddeath