Killing a Java thread by throwing exception

╄→尐↘猪︶ㄣ 提交于 2019-12-13 09:37:12

问题


I think killing a thread at precisely the time you want is a problem for many people. I recently ran across a way to kill a thread by throwing an exception. What are your thoughts/inputs on this? Has anyone implemented something like this before?


回答1:


The best way to stop a thread is to throw a InterruptedException from within the thread. If an exception is thrown this makes sure that catch and finally blocks are executed, so the thread is able to release locks and resources, close files and connections it has opened, etc.

Often you want to stop a thread from another thread. You should not use the Thread.stop() method, because it stops the thread immediately, resulting in deadlocks when the closed thread still own locks, files which are never closed, etc. The "official" way to stop a thread is to call the interrupt() method on the thread you want to stop. This sets an internal flag, which can be checked by Thread.interrupted(). Each thread should now poll Thread.interrupted() at convenient times and throw an InterruptedException if the flag is set:

if (Thread.interrupted()) throw new InterruptedException();  



回答2:


You should not kill a thread. You should make it stop. If you have a loop, you should stop this loop. If you have some time consuming function, like network connect, you should stop this network function instead of killing thread. There is no guarantee to stop a thread with Thread.stop() function



来源:https://stackoverflow.com/questions/27266249/killing-a-java-thread-by-throwing-exception

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