如何从java中的另一个线程立即杀死一个线程? [英] How to kill a thread immediately from another thread in java?

查看:171
本文介绍了如何从java中的另一个线程立即杀死一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何都要杀死一个线程或立即中断它。

就像在我的一个线程中一样,我调用一个需要时间执行的方法(2-4秒)。这个方法在while(布尔标志)块中,所以我可以从主线程中断它。

is there anyway to kill a thread or interrupt it immediately.
Like in one of my thread, i call a method which takes time to execute (2-4 seconds). This method is in a while(boolean flag) block, so i can interrupt it from the main thread.

但问题是,如果我打断它;它将等待执行循环结束,然后在下一次条件检查时,它将停止执行。

But the problem is, if i interrupt it; it will wait till the executing loop is finished and then on next conditional check, it will stop execution.

我希望它能够立即停止。反正有没有这样做?

I want it to stop right then. Is there anyway to do this?

推荐答案

如果您需要提前停止线程,则需要在线程中添加更多断点。

If you need the thread stop earlier you need to put more break points in your thread.

您可以使用stop()立即设置它,但这需要付出代价并且有许多可能的不良副作用。你可以非常小心地安全地使用stop(),但实际上你会发现更简单/更容易/更安全地放入更多的断点(你检查线程是否应该停止的点)

You can use stop() to styop it immediately, but this comes at a cost and has many possible undesirable side effects. You can use stop() safely with great care, but in reality you will find it simpler/easier/safer to put in more break points (points where you check if the thread should stop)

BTW,如果你想抛出一个不会被打印的错误,你可以使用ThreadDeath,因为这可以静默地关闭线程。

BTW, If you want to throw an error which won't be printed you can ThreadDeath as this can shutdown the thread silently.

这篇关于如何从java中的另一个线程立即杀死一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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