在java中为方法创建超时的最佳方法是什么?
我想在 x 秒后停止该方法。 我该怎么做?
编辑
我将详细说明: 我的 method() 要么是本机的,要么与其他服务器通信。
我没有陷入循环(因此我无法更改标志) 我想使用该方法的返回值(如果存在)。
I want to stop the method after x seconds.
How do I do it ?
EDIT
I will elaborate:
My method() is either native or communicates to other server.
I am not in a loop (Hence I cant change a flag)
I will want to use the return value of the method if it exists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这在很大程度上取决于您的方法正在做什么。最简单的方法是定期检查该方法已经执行了多长时间,并在超出限制时返回。
如果您想在单独的线程中运行该方法,那么您可以执行以下操作:
请注意,如果您在线程中执行一些不可中断的 IO,则此方法将不起作用。
That heavily depends on what your method is doing. The simplest approach would be to periodically check how long the method has been executing and return when the limit is exceeded.
If you want to run the method in a separate thread, then you could do something like this:
Please note that if you're doing some un-interruptible IO in the thread, this method will not work..
在我看来,最可靠的方法是多线程解决方案。我将长时间运行的算法放入 Runnable 中,并使用 ExecutorService 在给定的超时时间内执行线程。
此问题的答案提供了有关解决方案的更多详细信息。
当然,现在该方法将与主线程并行执行,但是您可以使用 Thread#join 强制执行单线程行为 - 只需等待主线程,直到时间有限的工作线程已完成或超出其超时限制。
The most reliable method - to my opinion - is a multithreading solution. I'd put the long running algorithm in a
Runnable
and useExecutorService
to execute the thread with a given timeout.Answers to this question provide more details on the solution.
Of course, now the method will be exectued in parallel to the main thread, but you can force single thread behaviour with
Thread#join
- simply wait with your main thread until the time limited worker thread has finished or exceeded it's timeout limit.这取决于您正在做什么以及您需要的准确性。
如果您处于循环中,您可以使用 System.currentTimeMillis() 跟踪已经过去了多少时间。只需获取开始时间并定期检查并查看已经过去了多长时间。
您可以生成一个新线程来开始处理,休眠 x 秒,然后执行某些操作来停止处理线程。
It depends on what you're doing and how accurate you need to be.
If you are in a loop, you can keep track of how much time has passed using System.currentTimeMillis(). Just get the time when you start and periodically check and see how long has passed.
You could spawn a new thread to start your processing, sleep for x seconds and then do something to stop the processing thread.
你不能在单次执行中这样做,你必须使用线程,因为
我同意armandino
看到这个
you can not do so in single execution you must use thread for that
i agree with armandino
see this