How I can replace deprecated method this.stop() in ThreadGroup

前端 未结 2 920
孤街浪徒
孤街浪徒 2021-01-17 02:49

I am working on java version upgrade project and I am on the work where I need to replace deprecated methods.

this.stop();

2条回答
  •  渐次进展
    2021-01-17 03:34

    Well I red a bit of the documentation about why stop() is deprecated and here is the most relevant part :

    This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply m>odifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.

    With those details, I think there is no more a simple way to stop all the threads as stop() did. You might need to modifie the threads so that you have a way to stop them (if it is possible for you).

提交回复
热议问题