识别和处置Java中锁定线程的最佳方法
-
28-09-2019 - |
题
我必须在新线程上调用功能第三方模块。从我所看到的,如果一切顺利,或者只是挂在线程上,请迅速完成。启动线程并拨打电话并等待几秒钟的好方法是什么,如果线程还活着,则假设它已锁定,杀死(或停止或放弃)线,而无需使用任何弃用的方法。
I have something like this for now, but I'm not sure if this is the best way to do it and I want to avoid calling Thread.stop() as it's deprecated.谢谢。
private void foo() throws Exception
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
// stuff that could potentially lock up the thread.
}
};
Thread thread;
thread = new Thread(runnable);
thread.start();
thread.join(3500);
if (thread.isAlive())
{
thread.stop();
throw new Exception();
}
}
解决方案
public void stop() {
if (thread != null) {
thread.interrupt();
}
}
请参阅此链接 关于如何停止线程,它很好地覆盖了主题
其他提示
没有办法做您想做的事情(无条件)。例如,如果是 stuff that could potentially lock up the thread.
看起来像这样,没有办法停止它,曾经没有system.exit():
public void badStuff() {
while (true) {
try {
wait();
}
catch (InterruptedException irex) {
}
}
}
当您的应用程序卡住时,运行JSTACK(或使用调试器)。尝试弄清楚什么可以粘上功能并修复它。
我会调查 java.util.concurrent
Executor
框架,特别是 Future<T>
界面。有了这些,您会从java.lang.thread的变化中抽象地抽象,并且您可以很好地脱钩,从而从它们的运行方式中获得了什么(无论是在单独的线程上,无论该线程,无论是线程来自池还是在池上进行实例化)飞行等)
至少将来的实例给了您 isDone
和 isCancelled
方法。
这 ExecutorService
(子接口的 Executor
)给您一些关闭任何外观任务的方法。或查看 ExecutorService.awaitTermination(long timeout, TimeUnit unit)
方法
private void foo() throws Exception
{
ExecutorService es = Executors.newFixedThreadPool(1);
Runnable runnable = new Runnable()
{
@Override
public void run()
{
// stuff that could potentially lock up the thread.
}
};
Future result = es.submit(runnable);
es.awaitTermination(30, TimeUnit.SECONDS);
if (!result.isDone()){
es.shutdownNow();
}
}