前言
问题背景:
主线程需要执行一些任务,不能影响主任务执行,这些任务有超时时间,当超过处理时间后,应该不予处理;如果未超时,应该获取到这些任务的执行结果;
一、编码思路
- 由于主线程正常执行不能影响,任务会处理很久,利用子线程处理
- 子线程运行后,应该有线程处理超时逻辑,超时后取消子线程
- 应有判断子线程在超时时间内,是否执行完成的逻辑,执行完成获取结果
二、使用步骤
直接上代码
代码如下(示例):
public class ComputeIfAbsentTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建一个单线程的线程池
ExecutorService executor = Executors.newSingleThreadExecutor();
// 提交任务并获取Future对象
Future<?> future = executor.submit(() -> {
// 子线程执行的任务
try {
// 模拟任务执行时间
Thread.sleep(5000); // 假设任务需要5秒钟完成
System.out.println(Thread.currentThread().getName());
return "处理完成";
} catch (InterruptedException e) {
// 如果任务被取消,中断异常会被抛出
System.out.println("Task interrupted.");
return "";
}
});
// 设置一个超时时间,如果任务在规定时间内没有完成,则会被取消
ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor();
schedule.schedule(() -> {
try {
if (future.isDone()) {
Object result = future.get(); // 获取结果
System.out.println("Result: " + result);
}else {
System.out.println(Thread.currentThread().getName());
// 取消任务
future.cancel(true);
System.out.println("Task timeout, cancelled.");
}
} catch (Exception e) {
e.printStackTrace();
}
}, 3000, TimeUnit.MILLISECONDS);// 设置超时时间为3秒
// 主线程继续执行其他操作
System.out.println("Main thread continues to execute.");
// 关闭线程池
executor.shutdown();
schedule.shutdown();
}
}
总结
利用Executors框架创建子线程执行任务;
利用Executors框架创建延时子线程监事执行任务的线程,通过超时时间判断 执行任务 子线程是否处理完成,处理完成获取结果,未处理完成,取消执行任务的子线程;