ExecutorService是一个继承Executor的接口,表示一个执行器。
方法说明:
Executor:
void execute(Runnable command);
执行之后不能获取返回值,(Runnable只用来执行,Callable接口才会有返回值)
ExecutorService:
1.关闭执行器
1.1 void shutdown();
a.之前提交的任务有序的被关闭,不保证之前任务能执行完成
b.关闭执行器,不再接收新任务。
c.已经关闭重复调用不生效
1.2 List<Runnable> shutdownNow();
a.尝试阻止所有执行的任务,
b.停止所有等待的任务,返回等待执行的任务列表
c.不等待执行的任务终止
2.关闭执行器后,可选择给未执行完成的任务一定时间,让其完成
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
shutdown之后一直阻塞到所有任务结束,参数是最大等待的时长和单位
3.查看执行器状态
3.1 boolean isShutdown();
if this executor has been shut down 执行器是否关闭
3.2 boolean isTerminated();
if all tasks have completed following shut down 执行器执行的任务是否全部结束
4.提交任务
4.1<T> Future<T> submit(Callable<T> task);
返回Future对象 用于判断是否执行结束(方法最前面的<T>是针对方法声明的泛型,声明参数及返回值的泛型)
4.2<T> Future<T> submit(Runnable task, T result);
返回Future对象 用于判断是否执行结束,参数result是返回结果
4.3Future<?> submit(Runnable task); (由于参数或返回值没使用泛型 用通配符Future<?>代替<T> Future<T>的写法)
返回Future对象 用于判断是否执行结束
5.执行任务
5.1<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
执行全部任务,返回任务状态或结果
5.2<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException;
设有超时时间的执行任务,如果到了时间,未完成的任务将被取消
5.3<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
执行所有任务,返回一个成功结束的任务(未出现异常),其他未完成任务将被取消
5.4<T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
设有超时时间的执行任务,返回一个超时之前成功结束的任务(未出现异常),其他未完成任务将被取消
6.下面列出ExecutorService主要的实现类:
ThreadPoolExecutor
ScheduledThreadPoolExecutor
ForkJoinPool
这些实现类都是AbstractExecutorService的子类,所以下一步研究AbstractExecutorService
网友评论