通过抛出异常来杀死Java线程 [英] Killing a Java thread by throwing exception

查看:281
本文介绍了通过抛出异常来杀死Java线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为在你想要的时候,要杀死一个线程是很多人的问题。我最近遇到一种方式,通过抛出一个异常来杀死线程。你的想法/意见是什么?有没有人实现过这样的东西?

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?

推荐答案

阻止线程的最好方法是抛出一个线程内的InterruptedException 。如果抛出异常,则确保执行 catch finally 块,因此线程可以释放锁资源,关闭文件和已经打开的连接等。

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.

通常你想从另一个线程停止一个线程。您应该不使用 Thread.stop()方法,因为它会立即停止线程,导致死锁时,闭合的线程仍然拥有锁定,从未关闭的文件等。阻止线程的官方方法是在要停止的线程上调用 interrupt()方法。这设置一个内部标志,可以通过 Thread.interrupted()进行检查。每个线程现在应该在方便的时候轮询 Thread.interrupted(),如果标志置位,则抛出一个 InterruptedException / p>

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();  

这篇关于通过抛出异常来杀死Java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆