使用Executors.newScheduledThreadPool(n)创建线程意味着什么?

时间:2016-11-11 12:09:27

标签: java multithreading

当我创建ExecutorService时,我使用其中一个工厂来创建线程,例如,我们有3个线程:

Executors.newScheduledThreadPool (3) 

当我们使用工厂时,资源和内存会发生什么?这些线程已经存在或者在我启动任务时创建它们?创建线程(本机代码)意味着什么?

1 个答案:

答案 0 :(得分:2)

它将创建并返回具有以下特征的ScheduledThreadPoolExecutor

This class specializes ThreadPoolExecutor implementation by

 1. Using a custom task type, ScheduledFutureTask for
    tasks, even those that don't require scheduling (i.e.,
    those submitted using ExecutorService execute, not
    ScheduledExecutorService methods) which are treated as
    delayed tasks with a delay of zero.

 2. Using a custom queue (DelayedWorkQueue) based on an
    unbounded DelayQueue. The lack of capacity constraint and
    the fact that corePoolSize and maximumPoolSize are
    effectively identical simplifies some execution mechanics
    (see delayedExecute) compared to ThreadPoolExecutor
    version.

    The DelayedWorkQueue class is defined below for the sake of
    ensuring that all elements are instances of
    RunnableScheduledFuture.  Since DelayQueue otherwise
    requires type be Delayed, but not necessarily Runnable, and
    the workQueue requires the opposite, we need to explicitly
    define a class that requires both to ensure that users don't
    add objects that aren't RunnableScheduledFutures via
    getQueue().add() etc.

 3. Supporting optional run-after-shutdown parameters, which
    leads to overrides of shutdown methods to remove and cancel
    tasks that should NOT be run after shutdown, as well as
    different recheck logic when task (re)submission overlaps
    with a shutdown.

 4. Task decoration methods to allow interception and
    instrumentation, which are needed because subclasses cannot
    otherwise override submit methods to get this effect. These
    don't have any impact on pool control logic though.

对于你的问题

These threads already exist or they create when I start the tasks?

corePoolSize的大小中会创建并汇集线程,在这种情况下为3。