How do you kill a Thread in Java?

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

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

16条回答
  •  深忆病人
    2020-11-21 06:36

    I want to add several observations, based on the comments that have accumulated.

    1. Thread.stop() will stop a thread if the security manager allows it.
    2. Thread.stop() is dangerous. Having said that, if you are working in a JEE environment and you have no control over the code being called, it may be necessary; see Why is Thread.stop deprecated?
    3. You should never stop stop a container worker thread. If you want to run code that tends to hang, (carefully) start a new daemon thread and monitor it, killing if necessary.
    4. stop() creates a new ThreadDeathError error on the calling thread and then throws that error on the target thread. Therefore, the stack trace is generally worthless.
    5. In JRE 6, stop() checks with the security manager and then calls stop1() that calls stop0(). stop0() is native code.
    6. As of Java 13 Thread.stop() has not been removed (yet), but Thread.stop(Throwable) was removed in Java 11. (mailing list, JDK-8204243)

提交回复
热议问题