7

当我在应用程序中有此代码时:

Executors.newFixedThreadPool(4);

但我从不使用这个线程池。空闲线程会消耗 CPU 时间吗?如果是这样 - 为什么?

4

2 回答 2

4

No, these threads are created lazily, or 'on-demand'. As stated in the documentation (emphasis mine):

On-demand construction

By default, even core threads are initially created and started only when new tasks arrive

Java provides methods to override this default and allow for eager creation, namely prestartCoreThread and prestartAllCoreThreads.


Once threads are actually created, idle ones (generally) won't take CPU time as there is no reason for them to be scheduled on a core when they have no work to do.

They will still hold on to some memory however, for their stack and whatnot.

于 2017-06-19T14:25:04.010 回答
4

javadoc指出:

创建一个线程池,该线程池重用在共享无界队列上运行的固定数量的线程。在任何时候,最多 nThreads 个线程将是活动的处理任务。

这可能会导致假设:我们并不确切知道。但是正如另一个答案清楚地发现的那样——我们可以知道,实现实际上是完全懒惰的。因此:

 ExecutorService service = Executors.newFixedThreadPool(4);

甚至不会导致很多设置。实施可以免费等待任何

 service.submit(...

即将发生。

另一方面,可以(理论上)立即创建该线程池,并且可以创建 4 个操作系统线程。如果是后者,所有这些线程都将处于空闲状态,因此它们不应消耗任何 CPU 资源。

但是,当然,正如 Elliott 正确指出的那样,创建池和(可能)创建 1 到 4 个线程的初始步骤需要 CPU 活动。

当然:线程是一种操作系统资源。因此,即使它们“仅存在”并且什么也不做;他们有那个“成本”。同样,这可能取决于操作系统是否会变成问题(例如达到某个“现有线程的最大数量”限制)。

最后:这让我很好奇,我查看了当前的 Java8 源代码(从newFixedThreadPoo()ThreadPoolExcecutor()DefaultThreadFactory)。如果我没记错的话:那些构造函数只为创建线程做准备

所以:“当前”实现是“完全”懒惰的;如果你真的只调用newFixedThreadPool()而不使用生成的 ExecutorService ......什么也没有发生(就创建新线程而言)。

于 2017-05-05T08:44:22.843 回答