如何在主线程上的 java 中的某些代码周围设置超时?

发布于 2024-07-20 02:05:37 字数 149 浏览 7 评论 0原文

我正在寻找与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

月隐月明月朦胧 2024-07-27 02:05:37

你不能只使用Java 计时器

线程安排任务以便将来在后台线程中执行的工具。 任务可以安排为一次性执行,也可以定期重复执行。

Cant you just use the Java Timer?

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

好多鱼好多余 2024-07-27 02:05:37

您可以创建一个 ThreadPoolExecutor,其中有一个 invokeAll 接收超时作为参数的方法。

You can create a ThreadPoolExecutor, which has an invokeAll method who recievs a timeout as a parameter.

不如归去 2024-07-27 02:05:37

您正在寻找的是 来自 Java 8 的 CompletableFuture(链接指向官方 JavaDoc)。

用法可能如下所示:

public static <V> Optional<V> of(PrivilegedAction<V> action, Duration duration) {

    final CompletableFuture<V> handler = CompletableFuture.supplyAsync(() -> action.run());
    V retval = null;
    try {
        retval = handler.get(duration.toMillis(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException te) {
    } catch (Exception e) {
        try {
            handler.cancel(true);
        } catch (CancellationException ce) {
        }
    }
    return Optional.ofNullable(retval);
}

我创建的 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:

public static <V> Optional<V> of(PrivilegedAction<V> action, Duration duration) {

    final CompletableFuture<V> handler = CompletableFuture.supplyAsync(() -> action.run());
    V retval = null;
    try {
        retval = handler.get(duration.toMillis(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException te) {
    } catch (Exception e) {
        try {
            handler.cancel(true);
        } catch (CancellationException ce) {
        }
    }
    return Optional.ofNullable(retval);
}

A util class I created: (German comments) DTimeout (View at pastebin)

衣神在巴黎 2024-07-27 02:05:37

要么在线程中运行它,要么执行如下操作:

void method() {
    long endTimeMillis = System.currentTimeMillis() + 10000;
    while (true) {
        // method logic
        if (System.currentTimeMillis() > endTimeMillis) {
            // do some clean-up
            return;
        }
    }
}

正如您所看到的,这并不适用于所有类型的方法。

Either run it in a Thread or do something like this:

void method() {
    long endTimeMillis = System.currentTimeMillis() + 10000;
    while (true) {
        // method logic
        if (System.currentTimeMillis() > endTimeMillis) {
            // do some clean-up
            return;
        }
    }
}

As you can see, this doesn't work for all kind of methods.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文