How to properly stop a thread, if my call to Thread.interrupt() will not work? [duplicate]

若如初见. 提交于 2019-11-30 22:15:14

If practical in your situation, spawn another process and treat that as the unit of work, rather than a thread. Process killing is much more deterministic, though devoting a process to what used to be a thread's work might be too heavyweight for your situation.

Pih

Why you do not try to use sleep(long timeout) when are waiting for some condition and if had not success, you simple "return" from the thread?


Probably your thread is running in a while (booleanVariable) { },

if it is, you could set this variable as volatile, and the thread controller set it as false.

Think of the Thread.stop() like the System.exit(value), it works, but when you have some bug making you thread stop/vm exit, will be much more harder to find it out.

The only solution better than using Thread.stop() is to use the library in a seperate thread which you can kill to stop it.

You may want to look for different handles of the function you are running, for example if its IO you can try to close any open connections/streams. If you are stuck with this library (IE can't find one that has better interruption mechanics) Thread.stop() is your only way of stopping the thread.

Thread.stop() is deprecated from java 4 onwards..I read an article to stop a thread by wrapping the call to the library in an separate class that implements InterruptibleChannel which is part of java.nio. Interruptibleclasses has close() method, through which another thread can call it asynchronously.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!