Java:在某段代码上设置超时? [英] Java: set timeout on a certain block of code?

查看:163
本文介绍了Java:在某段代码上设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些代码块运行时间超过可接受范围后,是否可以强制Java抛出异常?

Is it possible to force Java to throw an Exception after some block of code runs longer than acceptable?

推荐答案

是的,但强制另一个线程在随机代码行中断通常是一个非常糟糕的主意。如果你打算关闭这个过程,你只会这样做。

Yes, but its generally a very bad idea to force another thread to interrupt on a random line of code. You would only do this if you intend to shutdown the process.

你可以做的是 Thread.interrupt()任务是一定的时间。但是,除非代码检查它,否则它将无法工作。使用 Future.cancel(true)

What you can do is Thread.interrupt() a task are a certain amount of time. However, unless the code checks for this it won't work. An ExecutorService can make this easier with Future.cancel(true)

ExecutorService可以使代码更好地为时间本身并在需要时停止。

Its much better for the code to time itself and stop when it needs to.

这篇关于Java:在某段代码上设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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