aiaiask.com©

开花即结果 提问即答案

采用线程池处理业务,并且线程池中的任务超时关闭,不要阻塞主线程
原始问题:

采用线程池处理业务,并且线程池中的任务超时关闭,不要阻塞主线程

可以使用Java中的ThreadPoolExecutor来实现线程池处理业务,并且设置任务超时关闭。具体实现如下:

  1. 创建ThreadPoolExecutor对象,设置核心线程数、最大线程数、线程空闲时间、任务队列等参数。
ThreadPoolExecutor executor = new ThreadPoolExecutor(
    corePoolSize, // 核心线程数
    maximumPoolSize, // 最大线程数
    keepAliveTime, // 线程空闲时间
    TimeUnit.MILLISECONDS, // 时间单位
    new LinkedBlockingQueue<Runnable>() // 任务队列
);
  1. 提交任务到线程池中,使用Future对象获取任务执行结果。
Future<?> future = executor.submit(new Runnable() {
    @Override
    public void run() {
        // 业务处理逻辑
    }
});

try {
    // 获取任务执行结果,设置超时时间
    future.get(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
    // 线程中断异常
} catch (ExecutionException e) {
    // 任务执行异常
} catch (TimeoutException e) {
    // 任务超时异常,取消任务执行
    future.cancel(true);
}
  1. 关闭线程池,等待所有任务执行完成。
executor.shutdown();
try {
    if (!executor.awaitTermination(timeout, TimeUnit.MILLISECONDS)) {
        // 等待超时,强制关闭线程池
        executor.shutdownNow();
    }
} catch (InterruptedException e) {
    // 线程中断异常
    executor.shutdownNow();
}

通过以上实现,可以在不阻塞主线程的情况下,使用线程池处理业务,并且设置任务超时关闭。

采用线程池处理业务,并且线程池中的任务超时关闭,不要阻塞主线程
AI / 模型Siliconflow
时间 / DATEJune 2, 2023, 11:40 AM
语言zh-CN
IP / 区域广东 佛山