How do you kill a Thread in Java?

前端 未结 16 2357
天命终不由人
天命终不由人 2020-11-21 05:54

How do you kill a java.lang.Thread in Java?

16条回答
  •  被撕碎了的回忆
    2020-11-21 06:48

    In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.

    Often a volatile boolean field is used which the thread periodically checks and terminates when it is set to the corresponding value.

    I would not use a boolean to check whether the thread should terminate. If you use volatile as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.

    Certain blocking library methods support interruption.

    Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:

    public void run() {
       try {
          while (!interrupted()) {
             // ...
          }
       } catch (InterruptedException consumed)
          /* Allow thread to exit */
       }
    }
    
    public void cancel() { interrupt(); }
    

    Source code adapted from Java Concurrency in Practice. Since the cancel() method is public you can let another thread invoke this method as you wanted.

提交回复
热议问题