java是否保证核心池线程在ThreadPoolExecutor中始终保持 Activity 状态?
我多次运行了我的测试代码,但似乎不能保证。
我尝试使用allowCoreThreadTimeOut=true 和allowCoreThreadTimeOut = false。然而,行为没有改变。
这是我的测试代码。请尝试使用两个不同的 noOfTaskToRun 值 1 和 4。
public static void main(String[] args) {
int noOfTaskToRun = 1;
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 2000, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
executor.allowCoreThreadTimeOut(false);
List<Thread> threads = new ArrayList<Thread>();
for(int i = 0; i<noOfTaskToRun ; i++)
threads.add(new Thread("thread" + i) {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
for (Thread thread : threads) {
executor.execute(thread);
}
System.out.println("Before executor.getActiveCount(): "+ executor.getActiveCount());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("After executor.getActiveCount(): "+ executor.getActiveCount());
}
我将 keepAliveTime 修改为 2000。即使现在线程也超时了。
最佳答案
我实际上并不是 100% 确定,但我认为 getActiveCount()
并不是你所想的那样。
文档说:“返回正在主动执行任务的线程的大致数量。”因此,我的猜测是空闲线程不包含在该数字中,但仍然可以处于 Activity 状态。
您可能想要的是 getPoolSize()
:“返回池中当前的线程数。”
补充:如果您的任务 hibernate 5 秒,并且您给所有任务设置 5 秒超时,那么超时后有多少任务完成将是相当随机的...
关于java - ThreadPool 核心线程一旦创建就始终处于 Activity 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18572736/