线程池

2018-09-28  本文已影响0人  永远的太阳0123

2.ExecutorService
ExecutorService是Executor的子接口,在Executor接口的基础上添加了很多方法。
在定义一个线程池时,我们一般使用这个接口,大部分情况下这个接口的方法可以满足我们的需求。

public interface ExecutorService extends Executor {
    // 优雅关闭线程池。已经提交的任务继续执行,不接受之后提交的新任务
    void shutdown();
    // 立即关闭线程池。停止正在运行的所有任务,不接受之后提交的新任务
    List<Runnable> shutdownNow();
    // 线程池是否已经关闭
    boolean isShutdown();
    // 是否调用了shutdown或shutdownNow方法
    boolean isTerminated();
    // 等待所有任务完成,并设置超时时间
    // 在实际应用中,可以先调用shutdown方法,再调用这个方法等待所有任务完成,返回值代表有没有超时
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;
    // 提交一个Callable任务
    <T> Future<T> submit(Callable<T> task);
    // 提交一个Runnable任务,第二个参数会被放到Future中,作为返回值。
    <T> Future<T> submit(Runnable task, T result);
    // 提交一个Runnable任务
    Future<?> submit(Runnable task);
    // 执行所有任务,返回一个Future类型的list
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;
    // 也是执行所有任务,返回一个Future类型的list。这里设置了超时时间
    <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;
     // 只要有一个任务结束,方法就结束了,返回的是这个任务的结果。这里设置了超时时间,如果超时则抛出TimeoutException
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
上一篇 下一篇

猜你喜欢

热点阅读