1.Executor接口
/**
* 定义接口Executor
*/
public interface Executor {
/**
* 定义一个接收Runnable对象的方法executor,该方法接收一个Runable实例,它用来执行一个任务,
* 可以使用Executor而不用显示地创建线程:executor.execute(new RunnableTask());
*/
void execute(Runnable command);
}
2.ExecutorService接口
/**
* 定义ExecutorService接口 继承 Executor 接口
* 一个比Executor使用更广泛的子类接口
* 提供了生命周期管理的方法,返回 Future 对象
* 提供了可跟踪一个或多个异步任务执行状况返回Future的方法
*/
public interface ExecutorService extends Executor {
/**
* 关闭 ExecutorService 执行后ExecutorService停止接受新任务
* 且等待已经提交的任务执行完成(已经提交的任务会分两类:一类是已经在执行的,另一类是还没有开始执行的)
* 当所有已经提交的任务执行完毕后将会关闭ExecutorService
*/
void shutdown();
/**
* 关闭 ExecutorService 执行后ExecutorService阻止新来的任务提交,同时会中断当前正在运行的线程
* @return 被中断的线程列表
*/
List<Runnable> shutdownNow();
/**
* 是否已关闭
* 当调用shutdown()或shutdownNow()方法后返回为true
*/
boolean isShutdown();
/**
* 是否已全部关闭
* 当调用shutdown()方法后,并且所有提交的任务完成后返回为true;
* 当调用shutdownNow()方法后,成功停止后返回为true;
*/
boolean isTerminated();
/**
* 优雅的关闭,并允许关闭声明后新任务能提交
* 当前线程阻塞,直到
* 等所有已提交的任务(包括正在跑的和队列中等待的)执行完
* 或者等超时时间到
* 或者线程被中断,抛出InterruptedException
* 然后返回true(shutdown请求后所有任务执行完毕)或false(已超时)
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 提交一个线程
*/
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
/**
* 批量提交线程
*/
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) throws InterruptedException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
3.AbstractExecutorService
/**
* 定义抽象类AbstractExecutorService 实现 ExecutorService接口
*/
public abstract class AbstractExecutorService implements ExecutorService {
/**
* 创建一个RunnableFuture
* @param runnable 执行得线程
* @param value 返回值类型
*/
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
/**
* 创建一个RunnableFuture
*/
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
/**
* 提交任务 -Runnable
*/
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException(); //校验
RunnableFuture<Void> ftask = newTaskFor(task, null);//创建Future
execute(ftask); //调用execute方法 这里未实现
return ftask; //返回当前Future
}
/**
* 提交任务 -Runnable result
*/
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();//校验
RunnableFuture<T> ftask = newTaskFor(task, result);//创建Future
execute(ftask); //调用execute方法 这里未实现
return ftask; //返回当前Future
}
/**
* 提交任务 -Callable
*/
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException(); //校验
RunnableFuture<T> ftask = newTaskFor(task); //创建Future
execute(ftask); //调用execute方法 这里未实现
return ftask; //返回当前Future
}
private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks,
boolean timed, long nanos)
throws InterruptedException, ExecutionException, TimeoutException {
if (tasks == null)
throw new NullPointerException();
int ntasks = tasks.size();
if (ntasks == 0)
throw new IllegalArgumentException();
ArrayList<Future<T>> futures = new ArrayList<Future<T>>(ntasks);
ExecutorCompletionService<T> ecs =
new ExecutorCompletionService<T>(this);
try {
ExecutionException ee = null;
final long deadline = timed ? System.nanoTime() + nanos : 0L;
Iterator<? extends Callable<T>> it = tasks.iterator();
futures.add(ecs.submit(it.next()));
--ntasks;
int active = 1;
for (;;) {
Future<T> f = ecs.poll();
if (f == null) {
if (ntasks > 0) {
--ntasks;
futures.add(ecs.submit(it.next()));
++active;
}
else if (active == 0)
break;
else if (timed) {
f = ecs.poll(nanos, TimeUnit.NANOSECONDS);
if (f == null)
throw new TimeoutException();
nanos = deadline - System.nanoTime();
}
else
f = ecs.take();
}
if (f != null) {
--active;
try {
return f.get();
} catch (ExecutionException eex) {
ee = eex;
} catch (RuntimeException rex) {
ee = new ExecutionException(rex);
}
}
}
// if (ee == null)
// ee = new ExecutionException();
throw ee;
} finally {
for (int i = 0, size = futures.size(); i < size; i++)
futures.get(i).cancel(true);
}
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
try {
return doInvokeAny(tasks, false, 0);
} catch (TimeoutException cannotHappen) {
assert false;
return null;
}
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return doInvokeAny(tasks, true, unit.toNanos(timeout));
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
if (tasks == null)
throw new NullPointerException();
ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
boolean done = false;
try {
for (Callable<T> t : tasks) {
RunnableFuture<T> f = newTaskFor(t);
futures.add(f);
execute(f);
}
for (int i = 0, size = futures.size(); i < size; i++) {
Future<T> f = futures.get(i);
if (!f.isDone()) {
try {
f.get();
} catch (CancellationException ignore) {
} catch (ExecutionException ignore) {
}
}
}
done = true;
return futures;
} finally {
if (!done)
for (int i = 0, size = futures.size(); i < size; i++)
futures.get(i).cancel(true);
}
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException {
if (tasks == null)
throw new NullPointerException();
long nanos = unit.toNanos(timeout);
ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
boolean done = false;
try {
for (Callable<T> t : tasks)
futures.add(newTaskFor(t));
final long deadline = System.nanoTime() + nanos;
final int size = futures.size();
// Interleave time checks and calls to execute in case
// executor doesn't have any/much parallelism.
for (int i = 0; i < size; i++) {
execute((Runnable)futures.get(i));
nanos = deadline - System.nanoTime();
if (nanos <= 0L)
return futures;
}
for (int i = 0; i < size; i++) {
Future<T> f = futures.get(i);
if (!f.isDone()) {
if (nanos <= 0L)
return futures;
try {
f.get(nanos, TimeUnit.NANOSECONDS);
} catch (CancellationException ignore) {
} catch (ExecutionException ignore) {
} catch (TimeoutException toe) {
return futures;
}
nanos = deadline - System.nanoTime();
}
}
done = true;
return futures;
} finally {
if (!done)
for (int i = 0, size = futures.size(); i < size; i++)
futures.get(i).cancel(true);
}
}
}