public interface Executor {
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
/*
* 不再接受新任务
* 当所有已提交任务执行完后,就关闭
* 如果已经关闭,则调用没有其他作用
*/
void shutdown();
/*
* 试图停止所有正在执行的活动任务,暂停处理正在等待的任务
* 并返回等待执行的任务列表
*/
List shutdownNow();
boolean isShutdown();
boolean isTerminated();
//所有任务完成后shutdown,或者超时interrupted后会shutdown
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
// 提交任务
Future submit(Callable task);
Future submit(Runnable task, T result);
Future> submit(Runnable task);
// 批量提交任务
List> invokeAll(Collection extends Callable> tasks)
throws InterruptedException;
List> invokeAll(Collection extends Callable> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
T invokeAny(Collection extends Callable> tasks)
throws InterruptedException, ExecutionException;
T invokeAny(Collection extends Callable> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
Executor
ExecutorService
AbstractExecutorService
ThreadPoolExecutor
线程池通过Executors类创建出不同线程池,默认四种线程池创建方法都是默认给开发者配置好了相应参数,通过不同参数使用构造方法最终构造出我们看到的不同线程池。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
不同参数构造方法,上面线程池都是调用以下方法构建的 ,最终也是调用到下面构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
(1)corePoolSize与maximumPoolSize
(2)keepAliveTime与unit
(3)workQueue
正在执行的线程小于corePoolSize,创建新线程
正在执行的线程大于等于corePoolSize,把任务添加到阻塞队列
阻塞队列满了,且正在执行的线程小于maximumPoolSize,创建新线程
否则拒绝任务
阻塞队列类型
(4)threadFactory
(5)handler
public interface ThreadFactory {
/**
* 创建一个线程接口
*/
Thread newThread(Runnable r);
}
默认线程创建工厂
private static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
/**
* 创建线程组,线程名,和stackSize
*/
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
/**
* 默认不是后台线程
*/
if (t.isDaemon())
t.setDaemon(false);
/**
* 如果不是normal优先级则设置normal优先级
*/
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
private static class PrivilegedThreadFactory extends DefaultThreadFactory {
final AccessControlContext acc;
final ClassLoader ccl;
PrivilegedThreadFactory() {
super();
/**
* 获取类加载器
*/
this.acc = AccessController.getContext();
this.ccl = Thread.currentThread().getContextClassLoader();
}
public Thread newThread(final Runnable r) {
return super.newThread(new Runnable() {
/**
* 创建一个线程以后在runable里面调用submit过来的runnable执行体
*/
public void run() {
AccessController.doPrivileged(new PrivilegedAction() {
public Void run() {
Thread.currentThread().setContextClassLoader(ccl);
r.run();
return null;
}
}, acc);
}
});
}
}
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
//如果当前任务数小于核心线程数
if (workerCountOf(c) < corePoolSize) {
//开启新线程执行任务
if (addWorker(command, true))
return;
c = ctl.get();
}
// 线程数大于corePoolSize,或者新建线程不成功,条件任务队列
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
// 如果此时ThreadPoolExecutor已经关闭了
if (! isRunning(recheck) && remove(command))
reject(command);
// 或者线程均被释放了,新建一个线程
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 阻塞队列满了,则尝试新建非core线程
else if (!addWorker(command, false))
reject(command);
}
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// 如果线程池是不是关闭,当前添加任务为空,任务队列为空,则说明没有要添加的新任务
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
//创建任务对象
w = new Worker(firstTask);
//获取任务线程
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
//将任务添加到正在执行任务列表中
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
//启动线程执行任务
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
....
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
//通过ThreadFactory创建一个新线程,键
this.thread = getThreadFactory().newThread(this);
}
//线程执行体
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);
}
}
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
// Callable包装成一个FutureTask,然后提交给execute函数执行
public Future submit(Callable task) {
if (task == null) throw new NullPointerException();
// 把Callable包装成一个FutureTask
RunnableFuture ftask = newTaskFor(task);
// 通过execute调用
execute(ftask);
return ftask;
}