java - 对 ThreadPoolExecutor 内的各个线程设置超时

标签 java multithreading threadpool

我正在使用 java api 中的 threadPoolExecutor 类来处理我的所有线程。目前我有 5 个线程可以存在于线程池中。我的线程都在执行相同的任务。他们正在向数据库发出请求并等待回复。有时数据库一段时间没有回复。这意味着这些线程被困在线程池中等待。

我想知道是否有任何方法可以为线程池中的线程设置超时。因此,如果一个线程运行超过半小时,那么线程池将杀死它并处理队列中的下一个线程。我没有

目前,线程池内的线程有自己的计时器任务,该任务会写入日志,说明该线程花费了超过 30 分钟。我正在尝试想出一种方法来杀死花费这么长时间的线程。

我怎样才能做到这一点!

最佳答案

Keep-alive times

If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime (see getKeepAliveTime(java.util.concurrent.TimeUnit)). This provides a means of reducing resource consumption when the pool is not being actively used. If the pool becomes more active later, new threads will be constructed. This parameter can also be changed dynamically using method setKeepAliveTime(long, java.util.concurrent.TimeUnit). Using a value of Long.MAX_VALUE TimeUnit.NANOSECONDS effectively disables idle threads from ever terminating prior to shut down. By default, the keep-alive policy applies only when there are more than corePoolSizeThreads. But method allowCoreThreadTimeOut(boolean) can be used to apply this time-out policy to core threads as well, so long as the keepAliveTime value is non-zero.

来自ThreadPoolExecutor Java 文档

关于java - 对 ThreadPoolExecutor 内的各个线程设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11789319/

相关文章:

python - 使用 ThreadPool Python 时的最大池大小

java - Spring Batch - 如何使用从 REST API 请求收到的文件名启 Action 业

java - 从Java中的字符串数组中提取

java - Glassfish 3.1 中未找到通用资源适配器 genericra.rar

c++ - 标准 C++ 中的共享递归互斥锁

android - 主线程和UI线程的区别

c++ - 如何在 Windows 中的私有(private)管理池中设置线程优先级?

java - 警报管理器有时会在错误的时间触发

C++11 线程,它是有效代码吗?