ExecutorService.submit如何工作

时间:2017-05-23 06:55:25

标签: java multithreading

我试图了解Executor.submit(Runnable)的工作原理。假设我们使用ExecutorService创建一个大小为2的线程池。

我们有一个名为 Runner实现Runnable 的类。

ExecutorService.newFixedThreadPool(2);
for (int i = 0; i <5; i++){
  ExecutorService.submit(new Runner());
}

当我们做新的Runner()时,我们是不是已经创建了5个线程?

那么在这种情况下ExecutorService如何提供帮助?

3 个答案:

答案 0 :(得分:3)

该服务使用队列来存储传入的Runnable对象。一旦线程可用于工作,服务就会使用该线程执行到期的下一个 Runnable 对象。

Runnables 主题。您的示例将创建构成池的两个线程;然后随着时间的推移,5个Runner对象将被分派到这两个线程中的一个。

这就是全部。

答案 1 :(得分:1)

您可以从grepcode检查AbstractExecutorService的实现。

AbstractExecutorServiceThreadPoolExecutor的基类,它实现了ExecutorService

public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Object> ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    return new FutureTask<T>(runnable, value);
}
来自execute

ThreadPoolExecutor实施

 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);

/**
 * Checks if a new worker can be added with respect to current
 * pool state and the given bound (either core or maximum). If so,
 * the worker count is adjusted accordingly, and, if possible, a
 * new worker is created and started running firstTask as its
 * first task. This method returns false if the pool is stopped or
 * eligible to shut down. It also returns false if the thread
 * factory fails to create a thread when asked, which requires a
 * backout of workerCount, and a recheck for termination, in case
 * the existence of this worker was holding up termination.
 *
 * @param firstTask the task the new thread should run first (or
 * null if none). Workers are created with an initial first task
 * (in method execute()) to bypass queuing when there are fewer
 * than corePoolSize threads (in which case we always start one),
 * or when the queue is full (in which case we must bypass queue).
 * Initially idle threads are usually created via
 * prestartCoreThread or to replace other dying workers.
 *
 * @param core if true use corePoolSize as bound, else
 * maximumPoolSize. (A boolean indicator is used here rather than a
 * value to ensure reads of fresh values after checking other pool
 * state).
 * @return true if successful
 */

 private boolean addWorker(Runnable firstTask, boolean core)

检查同一班级中Worker的实施情况

/**
 * Class Worker mainly maintains interrupt control state for
 * threads running tasks, along with other minor bookkeeping.
 * This class opportunistically extends AbstractQueuedSynchronizer
 * to simplify acquiring and releasing a lock surrounding each
 * task execution.  This protects against interrupts that are
 * intended to wake up a worker thread waiting for a task from
 * instead interrupting a task being run.  We implement a simple
 * non-reentrant mutual exclusion lock rather than use ReentrantLock
 * because we do not want worker tasks to be able to reacquire the
 * lock when they invoke pool control methods like setCorePoolSize.
 */

答案 2 :(得分:0)

不在创建2个线程的线程池,Executor Service将等到池中有可用线程将下一个任务提交给可用线程。