我的线程池大小为 3,如下所示,在构造函数中我使用相同的线程池来启动两个不同的线程:
- 一种是调用实现
Runnable
接口(interface)的Poller
类。 - 其他是每 1 秒启动一个线程运行。
下面是我的代码:
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
private Data() {
executorService.submit(new Poller());
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
for (Entry<Long, byte[]> entry : retryHolder.asMap().entrySet()) {
execute(entry.getKey(), entry.getValue());
}
}
}, 0, 1, TimeUnit.SECONDS);
}
我的问题是我需要大小为 3 的线程池还是我可以只使用 2 个线程池?因为我知道根据我上面的代码它只会使用两个线程,所以显然我可能会浪费另一个线程?
最佳答案
根据scheduleAtFixedRate
的文档:
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
因此,您在池中仅使用 2 个线程就可以了,但在池中使用 3 个线程可能只会带来最小的(如果有的话)性能/开销损失。
关于java - 了解执行器服务中的线程池大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47025691/