文章目录
- 前言
- 一、编码思路
- 二、使用步骤
- 直接上代码
- 总结
前言
问题背景:
主线程需要执行一些任务,不能影响主任务执行,这些任务有超时时间,当超过处理时间后,应该不予处理;如果未超时,应该获取到这些任务的执行结果;
一、编码思路
- 由于主线程正常执行不能影响,任务会处理很久,利用子线程处理
- 子线程运行后,应该有线程处理超时逻辑,超时后取消子线程
- 应有判断子线程在超时时间内,是否执行完成的逻辑,执行完成获取结果
二、使用步骤
直接上代码
代码如下(示例):
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框架创建延时子线程监事执行任务的线程,通过超时时间判断 执行任务 子线程是否处理完成,处理完成获取结果,未处理完成,取消执行任务的子线程;