Java实现任务超时处理方法
作者:不才黄某 时间:2023-01-09 14:46:45
任务超时处理是比较常见的需求,比如在进行一些比较耗时的操作(如网络请求)或者在占用一些比较宝贵的资源(如数据库连接)时,我们通常需要给这些操作设置一个超时时间,当执行时长超过设置的阈值的时候,就终止操作并回收资源。Java中对超时任务的处理有两种方式:一种是基于异步任务结果的超时获取,一种则是使用延时任务来终止超时操作。下文将详细说明。
一、基于异步任务结果的超时获取
基于异步任务结果的获取通常是跟线程池一起使用的,我们向线程池提交任务时会返回一个Future对象,在调用Future的get方法时,可以设置一个超时时间,如果超过设置的时间任务还没结束,就抛出异常。接下来看代码:
public class FutureDemo {
static ExecutorService executorService= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2);
public static void main(String[] args) {
Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
System.out.println("任务被中断。");
}
return "OK";
}
});
try {
String result = future.get(2, TimeUnit.SECONDS);
} catch (InterruptedException |ExecutionException | TimeoutException e) {
future.cancel(true);
System.out.println("任务超时。");
}finally {
System.out.println("清理资源。");
}
}}
运行代码,输出如下:
二、使用延时任务来终止超时操作
还有一种实现任务超时处理的思路是在提交任务之前先设置一个定时器,这个定时器会在设置的时间间隔之后去取消任务。当然如果任务在规定的时间内完成了,要记得取消定时器。首先来看一下我们的工作线程:
public class RunningTask {
private volatile boolean isStop;
public void stop(){
this.isStop=true;
}
public void doing() {
int i=1;
while (!isStop){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
}
System.out.println("任务被中断。");
}
}
这个工作线程每隔一秒钟会去检查下isStop变量,因此我们可以通过isStop变量来取消任务。至于取消任务的逻辑我们放在了定时器里面,代码如下:
public class CancelTask implements Runnable {
private RunningTask runningTask;
public CancelTask(RunningTask runningTask) {
this.runningTask = runningTask;
}
@Override
public void run() {
runningTask.stop();
}
}
可以看到,该定时器的作用就是在一定的时间之后去中断工作线程的运行。接下来测试一下:
public class ScheduleDemo {
static ScheduledExecutorService executorService= Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors()*2);
public static void main(String[] args) {
RunningTask runningTask=new RunningTask();
ScheduledFuture<?> scheduledFuture = executorService.schedule(new CancelTask(runningTask), 3, TimeUnit.SECONDS);
runningTask.doing();
if(!scheduledFuture.isDone()){
scheduledFuture.cancel(true);
}
}
}
运行结果如下:
可以看到,任务在超时之后也可以被取消。
总结
以上所述是小编给大家介绍的Java实现任务超时处理方法,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://www.cnblogs.com/hzjjames/p/java_timeout.html?utm_source=debugrun&utm_medium=referral
标签:java,任务,超时
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解二维码生成工厂
2022-09-26 11:26:13
分布式医疗挂号系统SpringCache与Redis为数据字典添加缓存
2023-06-28 02:26:55
![](https://img.aspxhome.com/file/2023/5/57405_0s.png)
Android操作SQLite数据库(增、删、改、查、分页等)及ListView显示数据的方法详解
2022-11-28 10:03:09
![](https://img.aspxhome.com/file/2023/7/91717_0s.jpg)
SpringBoot整合Swagger的方法示例
2021-05-29 02:42:16
java判断字符串相等的方法
2023-05-19 14:08:30
Java SpringBoot的相关知识点详解
2023-11-23 02:36:35
![](https://img.aspxhome.com/file/2023/0/58620_0s.png)
java常量字符串过长报错的解决办法以及原因分析
2023-10-18 10:15:25
![](https://img.aspxhome.com/file/2023/2/80922_0s.png)
Android仿百度福袋红包界面
2023-11-01 04:53:01
![](https://img.aspxhome.com/file/2023/2/138232_0s.jpg)
java随机生成8位数授权码的实例
2022-04-24 12:03:47
android实现简单拼图游戏
2021-11-17 09:28:23
![](https://img.aspxhome.com/file/2023/9/95969_0s.jpg)
在C#中global关键字的作用及其用法
2021-12-24 04:33:19
使用@RequestBody配合@Valid校验入参参数
2023-05-04 22:36:09
![](https://img.aspxhome.com/file/2023/2/60692_0s.png)
java 多态与抽象类详解总结
2022-04-19 10:59:18
![](https://img.aspxhome.com/file/2023/5/67135_0s.jpg)
c#线程同步使用详解示例
2021-06-15 19:22:58
HorizontalScrollView水平滚动控件使用方法详解
2023-02-19 21:12:27
![](https://img.aspxhome.com/file/2023/2/111712_0s.jpg)
C#实现根据年份计算生肖属相的方法
2023-04-01 01:12:06
基于Hadoop实现Knn算法
2023-11-27 04:01:20
![](https://img.aspxhome.com/file/2023/8/60048_0s.jpg)
java数据结构算法稀疏数组示例详解
2021-09-30 11:47:28
![](https://img.aspxhome.com/file/2023/6/67956_0s.png)
JAVA 实现二叉树(链式存储结构)
2022-02-18 11:35:21
![](https://img.aspxhome.com/file/2023/4/83024_0s.jpg)
java图形用户界面实现菜单功能
2023-11-23 11:50:58
![](https://img.aspxhome.com/file/2023/2/59032_0s.jpg)