繁体   English   中英

为 java 中的方法创建超时的最佳方法是什么?

[英]what is the best way to create a timeout to a method in java?

我想在 x 秒后停止该方法。 我该怎么做?

编辑
我将详细说明:我的 method() 要么是本机的,要么与其他服务器通信。
我不在循环中(因此我无法更改标志)如果存在,我将想要使用该方法的返回值。

这在很大程度上取决于您的方法在做什么。 最简单的方法是定期检查方法执行了多长时间,并在超出限制时返回。

long t0 = System.currentTimeMillis();
// do something
long t1 = System.currentTimeMillis();
if (t1-t0 > x*1000) {
    return;
}

如果要在单独的线程中运行该方法,则可以执行以下操作:

public <T> T myMethod() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        try {
            T value = executor.invokeAny(Collections.singleton(new Callable<T>() {
                @Override
                public T call() throws Exception {
                    //your actual method code here
                    return null;
                }
            }), 3, TimeUnit.SECONDS);
            System.out.println("All went fine");
            return value;
        } catch (TimeoutException e) {
            System.out.println("Exceeded time limit, interrupted");
        } catch (Exception e) {
            System.out.println("Some error happened, handle it properly");
        }
        return null; /*some default value*/
    } finally {
        executor.shutdownNow();
    }
}

请注意,如果您在线程中执行一些不可中断的 IO,则此方法将不起作用..

在我看来,最可靠的方法是多线程解决方案。 我将长时间运行的算法放在Runnable中,并使用ExecutorService以给定的超时时间执行线程。

此问题的答案提供了有关解决方案的更多详细信息。

当然,现在该方法将与主线程并行执行,但您可以使用Thread#join强制执行单线程行为- 只需等待您的主线程,直到时间有限的工作线程完成或超过其超时限制。

这取决于你在做什么以及你需要有多准确。 如果您处于循环中,您可以使用 System.currentTimeMillis() 来跟踪已经过去了多少时间。 只需获取您开始的时间并定期检查并查看已经过去了多长时间。

您可以生成一个新线程来开始处理,休眠 x 秒,然后做一些事情来停止处理线程。

您不能在单次执行中这样做,您必须为此使用线程

我同意阿曼迪诺

看到这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM