- java线程创建方式
- 线程池体系
- Executor
- ExecutorService
- AbstractExecutorService
- 继承thread
- 实现runable接口
- 实现callable和future
抽象出定义一个执行无返回值的任务方法
public interface Executor {
void execute(Runnable command);
}
ExecutorService
抽象出定义了线程池的动作
public interface ExecutorService extends Executor {
//关闭
void shutdown();
List shutdownNow();
boolean isShutdown();
boolean isTerminated();
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;
}
AbstractExecutorService
使用模板方法抽象定义了一些线程池常用的方法,都会调用子类实现的execute(ftask)方法。
publicFuture submit(Callable task) { if (task == null) throw new NullPointerException(); RunnableFuture ftask = newTaskFor(task); execute(ftask); return ftask; } ## RunnableFuture ftask = newTaskFor(task); protected RunnableFuture newTaskFor(Callable callable) { return new FutureTask (callable); }
FutureTask继承关系:
Future接口定义了一些获取结果的包装方法。
public interface Future{ boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }



