java设置超时_Java:如何实现代码超时功能?

本文介绍了一个自定义的`TimeoutCallable`类,该类实现了`Callable`接口并添加了超时功能。当指定的任务超过设定的超时时限,它将返回预设的超时值。通过`ExecutorService`来提交和执行`TimeoutCallable`实例,并展示了一个示例,展示了如何在任务超时时获取结果或打印超时信息。
摘要由CSDN通过智能技术生成

我们写一个有超时功能的 Callable:

import java.util.concurrent.*;

public class TimeoutCallable implements Callable {

private final Callable callable;

private final V timeoutV;

private final long timeout;

/**

* 构造一个 TimeoutCallable

*

* @param callable 要运行的 Callable

* @param timeout Callable 的最大运行时间

* @param timeoutV Callable 超时的返回结果

*/

public TimeoutCallable(Callable callable, long timeout, V timeoutV) {

this.timeout = timeout;

this.callable = callable;

this.timeoutV = timeoutV;

}

@Override

public V call() throws Exception {

ExecutorService executor = Executors.newSingleThreadExecutor();

Future future = executor.submit(callable);

V v = null;

try {

v = future.get(timeout, TimeUnit.MILLISECONDS);

} catch (TimeoutException ex) {

System.out.println("Callble 超时");

}

executor.shutdownNow(); // 给线程池中所有正在运行的线程发送 中断 信号

return v != null ? v : timeoutV;

}

}

然后试验:

import java.util.concurrent.*;

public class Test {

public static void main(String[] args) throws Exception {

Callable callable = () -> {

int N = 4;

int sum = 0;

for (int i = 0; i < N; i++) {

// Thread.sleep 方法是可以响应中断的,

// 如果你的代码需要“超时则线程结束”的效果,那么你的代码也应该要能够响应中断

Thread.sleep(1000);

sum += i;

}

return sum;

};

// 代码2, 代码2 运行的最长时间为 timeout

int timeout = 3000;

Integer timeoutValue = -1;

TimeoutCallable timeoutCallable = new TimeoutCallable<>(callable, timeout, timeoutValue);

ExecutorService executor = Executors.newSingleThreadExecutor();

Future future = executor.submit(timeoutCallable);

Integer result = future.get();

executor.shutdown();

// end 代码2

// 代码3

if (timeoutValue.equals(result)) {

System.out.println("--任务超时--");

} else {

System.out.println("任务结果:" + result);

}

// end 代码3

}

}

callable 的运行时间为 4 s,但我们设置的超时时间为 3 s,所以代码运行结果就是:

16a598131e7002b0800aad62da2f426e.png(可以看到 NetBeans 给出的运行时间是 3 s)

如果我们将 timeout 改成 5000(5 s),则结果是:

53e91550f03eb6fbd98cf3b6cd33625e.png(可以看到 NetBeans 给出的运行时间是 4 s)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值