java : 停止安全线程;不使用 while 和布尔标志 [英] java : stop safety a thread; not using while and boolean flag

查看:47
本文介绍了java : 停止安全线程;不使用 while 和布尔标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程只执行一次任务.如果它不能在适当的时候做到这一点,我想停止它.我怎样才能做到这一点?我之前看到的所有方法都使用了一个 while 循环和一个标志来表示一个多次完成的任务;但我的任务不是那样.

I have a thread that does it's task just one time. I want to stop it if it was not able to do that in an appropriate time. How can I do that? All the methods I have seen before used a while loop and a flag for a task that is done several times; but my task is not like that.

谢谢大家.

推荐答案

停止任务的唯一干净方法是中断它(或设置一些其他标志),这会导致线程正常停止.如果您的代码中没有外循环,您可以在可以安全中断工作流程的各个关键点进行检查.对于大型代码库来说,这可能很乏味,但这是最好的方法.

The only clean way of stopping a task is to interrupt it (or set some other flag) which causes the thread to gracefully stop. If you don't have an outer loop in your code you can check it at various key points where it is safe to interrupt the work flow. This can be tedious for a large code base, but it is the best approach.

如果你有一个你无法控制的库,你可以使用 Thread.stop() 但是这会使你的应用程序处于未定义状态.它不会像这样杀死线程,但会触发 ThreadDeath 错误,该错误将展开堆栈并调用 finally 块等.问题是它会发生在有效随机的代码行中(甚至是代码行的一半)线程可以根据代码的编写方式忽略 ThreadDeath 错误.

If you have a library you have no control over you can use Thread.stop() however this can leave your application in an undefined state. It doesn't kill the thread as such but triggers a ThreadDeath error which will unwind the stack and call finally block etc. The problem is it will occur in an effectively random line of code (even half way through a line of code) A thread can ignore the ThreadDeath error depending on how the code is written.

解决此问题的唯一方法是在另一个进程中运行不受信任的代码,然后在该进程花费太长时间时终止该进程.这可能会留下临时文件,但这是一个更安全的选择.

The only way around this is to run you untrusted code in another process, and then kill that process when it has taken too long. This could leave temporary files but is a much safer option.

这篇关于java : 停止安全线程;不使用 while 和布尔标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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