java中的线程池。
1. 线程池概述
由于线程的创建和销毁都需要消耗时间和资源,所以java引入了线程池的机制,所谓的线程池就是维护一定数量的活着的线程,来执行那些新产生的需要执行的线程。
2. java中关于线程池的接口
Executor是线程池最顶端的接口。里面只有一个execute方法。用来执行提交的线程。
/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the <tt>Executor</tt> implementation.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution.
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
ExecutorService是Executor的子接口。在Executor的基础上添加了关闭线程池,批量执行并且获得返回值的方法,submit封装了execute方法。
ThreadPoolExecutor,实现了Executor和ExecutorService接口。我们使用的线程池都是使用的ThreadPoolExecutor对象。关于ThreadPoolExecutor这个类,是继承了抽象类AbstractExecutorService。在抽象类里面实现了submit方法。该submit方法调用了execute。
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
在ThreadPoolExecutor中有execute的具体实现。
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);
}
在ThreadPoolExecutor中,使用一个BlockingQueue来存放提交过来的线程:
private final BlockingQueue<Runnable> workQueue;
可以看出,当execute一个runnable的类时,不是直接运行该runnable的类,而是将其放在了workQueue里面。
在Executor的run方法里面,会去这个queue里面取task,然后执行。
public void run() {
runWorker(this);
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
当我使用ThreadPoolExecutor时候,一般不是自己创建,而是通过工具类Executors。Executors提供了创建不同线程池的方法。常用的有 newSingleThreadExecutor, newFixedThreadPool, newCachedThreadPool和 newScheduledThreadPool。