了解执行程序服务中的线程池大小

understanding of thread pool size in executor service

我的线程池大小为 3,如下所示,在构造函数中我使用相同的线程池来启动两个不同的线程:

下面是我的代码:

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 个线程可能只有极小的(如果有的话)performance/overhead缺点。