How to stop a thread that is running forever without any use

后端 未结 6 2066
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 14:58

In the below code, i have a while(true) loop. considering a situation where there is some code in the try block where the thread is supposed to perform some tasks which take

6条回答
  •  时光取名叫无心
    2020-12-07 15:44

    I recommend using Thread.interrupt() (as mentioned by @Bohemian). It has a couple of advantages over using ad-hoc flags:

    • You don't need to create and use an application-specific API to do this. (And interrupts are guaranteed thread-safe ...)

    • Thread.interrupt() will interrupt threads that are blocked in a wait() or a join, or possibly1 some blocking I/O calls.

    However, it is not a magic bullet. If the thread you are trying to stop is executing regular code, it needs to periodically check its interrupted() flag, or it won't no to stop. This leaves us in the same as boat as we are in with an ad-hoc flag mechanism. The thread has to cooperate, or it can't be (safely) stopped.

    1 - This is a murky area. On the one hand, there is an InterruptedIOException whose javadoc says "Signals that an I/O operation has been interrupted". On the other hand, the exception is not explicitly mentioned in the javadocs for the various java.io stream classes.


    It is true that some 3rd-party code may not deal with the interrupted flag properly, and interrupts may get "eaten" as a result. But you can check for that if you have source code. And the situation is not a lot different to the 3rd-party code not paying attention to your ad-hoc flag mechanism.


    I would NOT recommend using Thread.stop(). It is fundamentally flakey. Some people claim that it works for them, but IMO they are either dealing with a special case that works ... or they are being lucky.

提交回复
热议问题