美文网首页
Executor+ExecutorService+Abstrac

Executor+ExecutorService+Abstrac

作者: 永远的太阳0123 | 来源:发表于2018-12-17 15:01 被阅读0次

1 Executor接口

Executor接口中只定义了execute方法,execute方法没有返回值。

public interface Executor {
    void execute(Runnable command);
}

2 ExecutorService接口

ExecutorService接口是Executor接口的子接口。

public interface ExecutorService extends Executor {
    void shutdown();
    List<Runnable> shutdownNow();
    boolean isShutdown();
    boolean isTerminated();
    // awaitTermination方法可能阻塞当前线程
    // 如果线程池处于TERMINATED状态,则阻塞结束并返回true
    // 如果阻塞当前线程超过给定时间,则阻塞结束并返回false
    // 如果当前线程被中断,则阻塞结束并抛出InterruptedException
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    // submit方法有返回值
    // 提交一个Callable任务,返回值是一个Future对象;当Callable任务执行完毕,调用Future对象的get方法,返回call方法的返回值。
    <T> Future<T> submit(Callable<T> task);
    // 提交一个Runnable任务,返回值是一个Future对象;当Runnable任务执行完毕,调用Future对象的get方法,返回给定的result
    <T> Future<T> submit(Runnable task, T result);
    // 提交一个Runnable任务,返回值是一个Future对象;当Runnable任务执行完毕,调用Future对象的get方法,返回null
    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接口中的部分方法。

3.1 AbstractExecutorService中的newTaskFor方法

    // 将提交的任务包装成FutureTask
    // 子类中可以重写newTaskFor方法
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

3.2 AbstractExecutorService中的submit方法

调用submit方法时,传入的Runnable对象或Callable对象不是用来创建线程的。Runnable对象中的run方法和Callable对象中的call方法是需要执行的任务。线程池中执行任务的线程是ThreadPoolExecutor.Worker内部类中的线程对象。

    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        // 将提交的任务包装成FutureTask
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }
    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        // 将提交的任务包装成FutureTask
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        // 将提交的任务包装成FutureTask
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

4 ScheduledExecutorService接口

ScheduledExecutorService接口是ExecutorService接口的子接口。

public interface ScheduledExecutorService extends ExecutorService {
    // 执行一个一次性任务
    // command:command中的run方法是需要执行的任务
    // delay:执行任务的延迟
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);
    // 执行一个一次性任务
    // callable:callable中的call方法是需要执行的任务
    // delay:执行任务的延迟
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit);
    // 执行一个周期性任务
    // 计划中每一次开始执行任务的时间:initialDelay、initialDelay+period、initialDelay+2*period……
    // 如果某一次执行任务抛出异常,则禁止后续的执行。否则,只能通过取消任务或关闭线程池的方式结束任务
    // 如果某一次执行任务的时间超过了period,则推迟后续的执行。一个任务不会被两个线程同时执行
    // command:command中的run方法是需要执行的任务
    // initialDelay:第一次执行任务的延迟
    // period:前一次开始执行任务到下一次开始执行任务的时间
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);
    // 执行一个周期性任务
    // 如果某一次执行任务抛出异常,则禁止后续的执行。否则,只能通过取消任务或关闭线程池的方式结束任务
    // command:command中的run方法是需要执行的任务
    // initialDelay:第一次执行任务的延迟
    // delay:前一次执行任务完毕到下一次开始执行任务的时间
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);
}

5 Executors

Executors中的方法都是静态方法。

5.1 Executors中的newFixedThreadPool方法

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

5.2 Executors中的newSingleThreadExecutor方法

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }
5.2.1 Executors.FinalizableDelegatedExecutorService内部类

Executors.FinalizableDelegatedExecutorService继承了Executors.DelegatedExecutorService。

    static class FinalizableDelegatedExecutorService
        extends DelegatedExecutorService {
        FinalizableDelegatedExecutorService(ExecutorService executor) {
            super(executor);
        }
        protected void finalize() {
            super.shutdown();
        }
    }
5.2.2 Executors.DelegatedExecutorService内部类

Executors.DelegatedExecutorService继承了AbstractExecutorService。

    static class DelegatedExecutorService extends AbstractExecutorService {
        private final ExecutorService e;
        DelegatedExecutorService(ExecutorService executor) { e = executor; }
        public void execute(Runnable command) { e.execute(command); }
        public void shutdown() { e.shutdown(); }
        public List<Runnable> shutdownNow() { return e.shutdownNow(); }
        public boolean isShutdown() { return e.isShutdown(); }
        public boolean isTerminated() { return e.isTerminated(); }
        public boolean awaitTermination(long timeout, TimeUnit unit)
            throws InterruptedException {
            return e.awaitTermination(timeout, unit);
        }
        public Future<?> submit(Runnable task) {
            return e.submit(task);
        }
        public <T> Future<T> submit(Callable<T> task) {
            return e.submit(task);
        }
        public <T> Future<T> submit(Runnable task, T result) {
            return e.submit(task, result);
        }
        public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
            throws InterruptedException {
            return e.invokeAll(tasks);
        }
        public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                             long timeout, TimeUnit unit)
            throws InterruptedException {
            return e.invokeAll(tasks, timeout, unit);
        }
        public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException, ExecutionException {
            return e.invokeAny(tasks);
        }
        public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                               long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
            return e.invokeAny(tasks, timeout, unit);
        }
    }

5.3 Executors中的newCachedThreadPool方法

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }

5.4 Executors中的newSingleThreadScheduledExecutor方法

    public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
    }
    public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1, threadFactory));
    }
5.4.1 Executors.DelegatedScheduledExecutorService内部类

Executors.DelegatedScheduledExecutorService继承了Executors.DelegatedExecutorService,实现了ScheduledExecutorService接口(Executors.DelegatedExecutorService内部类请见5.2.2)。

    static class DelegatedScheduledExecutorService
            extends DelegatedExecutorService
            implements ScheduledExecutorService {
        private final ScheduledExecutorService e;
        DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
            super(executor);
            e = executor;
        }
        public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
            return e.schedule(command, delay, unit);
        }
        public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
            return e.schedule(callable, delay, unit);
        }
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
            return e.scheduleAtFixedRate(command, initialDelay, period, unit);
        }
        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
            return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
        }
    }

5.5 Executors中的newScheduledThreadPool方法

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    }

相关文章

网友评论

      本文标题:Executor+ExecutorService+Abstrac

      本文链接:https://www.haomeiwen.com/subject/gxfckqtx.html