我正在使用 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/