【发布时间】:2020-08-12 12:40:07
【问题描述】:
我一直在玩ThreadPoolExecutor。我需要一个返回当前正在运行的线程数的方法。所以我决定使用ThreadPoolExecutor#getActiveCount。
但是,当我测试我的方法时,我发现了一些有趣的东西:ThreadPoolExecutor#getActiveCount 总是等于 ThreadPoolExecutor#getPoolSize。
这是一个重现它的示例代码:
class ExecutorTest {
private ThreadPoolExecutor executor;
ExecutorTest() {
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
}
@Test
void test() {
executor.execute(makeRunnable(100, "1"));
printExecutorState();
executor.execute(makeRunnable(100, "2"));
printExecutorState();
executor.execute(makeRunnable(100, "3"));
printExecutorState();
executor.execute(makeRunnable(100, "4"));
printExecutorState();
System.out.println("==Changing thread core&max pool size==");
executor.setCorePoolSize(2);
executor.setMaximumPoolSize(2);
printExecutorState();
assertThat(executor.getMaximumPoolSize()).isEqualTo(2);
assertThat(executor.getActiveCount()).isEqualTo(4);
}
private Runnable makeRunnable(long workTime, String name) {
return () -> {
long startTime = System.currentTimeMillis();
System.out.println("Running " + name);
while (System.currentTimeMillis() - startTime < workTime) {
}
System.out.println("Exited " + name);
};
}
private void printExecutorState() {
int poolSize = executor.getPoolSize();
int corePoolSize = executor.getCorePoolSize();
int maxPoolSize = executor.getMaximumPoolSize();
int running = executor.getActiveCount();
String currentState = String.format(
"poolSize=%d, corePoolSize=%d, maxPoolSize=%d, running=%d",
poolSize,
corePoolSize,
maxPoolSize,
running
);
System.out.println(currentState);
}
}
它打印以下内容:
Running 1
poolSize=1, corePoolSize=10, maxPoolSize=10, running=1
Running 2
poolSize=2, corePoolSize=10, maxPoolSize=10, running=2
Running 3
poolSize=3, corePoolSize=10, maxPoolSize=10, running=3
Running 4
poolSize=4, corePoolSize=10, maxPoolSize=10, running=4
==Changing thread core&max pool size==
poolSize=4, corePoolSize=2, maxPoolSize=2, running=4
现在的问题是这些方法之间有什么区别?使用ThreadPoolExecutor#getPoolSize 来检索正在运行的线程数有意义吗?
【问题讨论】:
标签: java multithreading threadpoolexecutor