【并发编程】-- ExecutorService接口实现原理

78 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第25天,点击查看活动详情

ExecutorService接口原理

ExecutorService接口是Executor接口的次一级接口,在Executor接口中定义一个执行方法,ExecutorService接口中需要定义一些用于服务执行器的方法。

ExecutorService源码如下:

public interface ExecutorService extends Executor {
	void shutdown();
    List<Runnable> shutdownNow();
    boolean isShutdown();
    boolean isTerminated();
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;
    <T> Future<T> submit(Callable<T> task);
    Future<?> submit(Runnable 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;
}

解析各方法:

shutdown()方法:关闭服务。

shutdownNow()方法:立即关闭服务。

isShutdown()方法:判断服务是否调用了shutdown。

isTerminated()方法:判断服务是否完全终止。

awaitTermination(long timeout, TimeUnit unit)方法:等待当前服务停止。

submit(Callable task)方法:提交一个任务Callable task,返回一个存根。

submit(Runnable task)方法:提交一个任务Runnable task,返回一个存根。

submit(Runnable task, T result)方法:提交一个任务Runnable task和指定返回值的类型,返回一个定义类型的返回值。

invokeAll(Collection<? extends Callable> tasks)方法:提交一组callable任务执行,返回所有任务的存根。

invokeAll(Collection<? extends Callable> tasks, long timeout, TimeUnit unit)方法:提交一组任务Callable task,返回所有任务的存根,注意是这个包含了等待执行的时间。

invokeAny(Collection<? extends Callable> tasks)方法:提交一组任务,等待其中任何一个任务完成后返回。

invokeAny(Collection<? extends Callable> tasks, long timeout, TimeUnit unit)方法:提交一组任务,等待其中任何一个任务完成后返回,注意是这个包含了等待执行的时间。

ExecutorService继承了Executor,这表明了它既具备了执行器的特性,又增加了自身的功能,接口组合就是为了功能合并,增加了线程池的功能,那这个线程池叫做ExecutorService,即执行器服务。