Когда JVM фактически создает и запускает новый поток?
Это зависит от используемой вами среды. Если вы используете ThreadPoolExecutor
, который находится в JDK начиная с 1.5, пул потоков создается при первой отправленной задаче, а не при создании ThreadPoolExecutor
. Приведенный ниже фрагмент кода взят из java.util.concurrent.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);
}
Как JVM назначает новую задачу Runnable уже запущенному потоку?
Например, ThreadPoolExecutor
, она помещает задачу в workQueue
во-первых, это BlockingQueue
, созданный при создании ThreadPoolExecutor
, а затем, когда один из рабочих потоков в пуле потоков завершит последнюю задачу, он попытается извлечь задачу из workQueue
.
Но обратите внимание на то, что все работники сначала создаются с первоначальным заданием, они выполняют работу одновременно с созданием.
private boolean addWorker(Runnable firstTask, boolean core) {