我有一个线程池:
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/