java线程池任务超时问题

标签 java multithreading threadpool

我有一个线程池:

ThreadPoolExecutor pool = new ThreadPoolExecutor(cores, 50, 30L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3000));

然后我运行:

try {
    pool.execute(() -> 
{
  //Very very long task, fetching from an external URL
});
}catch(Exception e){
    e.printStackTrace();
}

我从未遇到过异常,并且此代码等待了几分钟。 我该怎么做才能让它在 30 秒内取消?

最佳答案

根据文档,第三个参数 keepAlive 并不指定线程池中特定任务的等待时间,而是指定空闲线程从池中释放之前的时间。

 * @param keepAliveTime when the number of threads is greater than
 *        the core, this is the maximum time that excess idle threads
 *        will wait for new tasks before terminating.

为了实现您想要的行为,您应该将任务包装在 FutureTask 中,然后将 future 的任务提交到线程池。在未来的任务中,您可以调用 get(timeout, timeunit)

FutureTask<T> task = new FutureTask<T>(c);
pool.execute(task);
return task.get(timeout, timeUnit);

关于java线程池任务超时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590587/

相关文章:

java - 如何将csv文件中的数据解析到容器中并搜索1个值并在java中检索其行上的其余值

Java – 服务器仅在客户端停止时响应

multithreading - Delphi 多线程消息循环

multithreading - 维护许多独立的长期运行任务的有效方法?

java - Java 程序中拥有多个 Executors.newCachedThreadPool() 是否安全?

java - 执行器服务设置标志以停止线程

java - 在下面的程序中检测和处理竞争条件

java - 如何使用 Spring WebServiceTemplate 禁用 SSL 证书检查?

java - 错误 400——错误请求

java - COMP SCI 101 - 使用 Printf 将字段居中