How to kill a java thread?

前端 未结 8 1956
一个人的身影
一个人的身影 2020-12-11 08:26

I google the solution for killing a java thread. And there exists two solutions:

  1. set a flag
  2. using Thread.interrupt

But both of them ar

相关标签:
8条回答
  • 2020-12-11 09:00

    You can invoke the stop method on the Thread object but it is strongly recommended that you don't. Read this: http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

    Do you have the freedom to make minor changes to the API? Is this blocking call CPU bound or IO bound? If it is IO bound and if you have access to the underlying socket/remote communication object, closing that object can do wonders. It is at least better than stopping the thread.

    0 讨论(0)
  • 2020-12-11 09:01

    In theory, you could call the deprecated Thread.stop() method. But beware that this could result in your application behaving in unexpected and unpredictable ways ... depending on what the third party library is actually doing. Thread.stop() and friends are fundamentally unsafe.

    The best solution is to modify the 3rd-party library to respond to Thread.interrupt. If you cannot, then ditch it and find / use a better library.

    0 讨论(0)
  • 2020-12-11 09:08

    Thread.interrupt() is the only safe method which is generally applicable. You can of course use other application-level signals (such as a conditional check on a volatile variable) to self-terminate. Other methods (such as all the deprecated Thread.xx methods) can pollute your application's state in non-deterministic ways, and would require reloading all application state.

    0 讨论(0)
  • 2020-12-11 09:08

    You can try Thread.stop(), but at your own risk. Optimally, the API you're calling should have a way to interrupt the operation if needed (which is what Thread.interrupt() is for if the API itself does not provide a cleaner way to interrupt its progress, have you tried it?).

    0 讨论(0)
  • 2020-12-11 09:12

    Spawn a separate process and kill it using OS facilities. You'll have to call into "C" to do it but it won't be much code. You didn't say what OS you are running on.

    0 讨论(0)
  • 2020-12-11 09:13

    In java.util.concurrent.FutureTask, the mechanism of cancellation by timeout is acted as throwing java.util.concurrent.TimeoutException.

    You may check out this as if there are something to be interrupted automatically by timeout.

    0 讨论(0)
提交回复
热议问题