如何在主线程上的 java 中的某些代码周围设置超时?
我正在寻找与 ruby 中相同的 java 功能:
SystemTimer.timeout_after(30.seconds) do 做一点事 我可以
通过分叉一个线程然后在一段时间后杀死它来实现这一点,但是有没有更简单的方法?
I'm looking for functionality in java identical to this in ruby:
SystemTimer.timeout_after(30.seconds) do
do something
end
i could achieve this by forking a thread and then killing it after a while, but is there a simpler way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能只使用Java 计时器?
Cant you just use the Java Timer?
您可以创建一个 ThreadPoolExecutor,其中有一个 invokeAll 接收超时作为参数的方法。
You can create a ThreadPoolExecutor, which has an invokeAll method who recievs a timeout as a parameter.
您正在寻找的是
来自 Java 8 的 CompletableFuture
(链接指向官方 JavaDoc)。用法可能如下所示:
我创建的 util 类:(德语注释)DTimeout(在pastebin查看)
What you are looking for is the
CompletableFuture<T>
(Link leads to official JavaDoc) from Java 8.Usage could look something like this:
A util class I created: (German comments) DTimeout (View at pastebin)
要么在线程中运行它,要么执行如下操作:
正如您所看到的,这并不适用于所有类型的方法。
Either run it in a Thread or do something like this:
As you can see, this doesn't work for all kind of methods.