Executor ExecutorService Executors

Posted loveer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Executor ExecutorService Executors相关的知识,希望对你有一定的参考价值。

Executor

public interface Executor 
    void execute(Runnable command);

ExecutorService

ExecutorService是一个接口,继承了Executor接口,定义了一些生命周期的方法

public interface ExecutorService extends Executor 

    //顺次地关闭ExecutorService,停止接收新的任务,等待所有已经提交的任务执行完毕之后,关闭ExecutorService
    void shutdown();

    //阻止等待任务启动并试图停止当前正在执行的任务,停止接收新的任务,返回处于等待的任务列表
    List<Runnable> shutdownNow();

    //判断线程池是否已经关闭
    boolean isShutdown();

    //如果关闭后所有任务都已完成,则返回 true。注意,除非首先调用 shutdown 或 shutdownNow,否则 isTerminated 永不为 true。
    boolean isTerminated();

    //等待(阻塞)直到关闭或最长等待时间或发生中断,如果此执行程序终止,则返回 true;如果终止前超时期满,则返回 false
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    //提交一个返回值的任务用于执行,返回一个表示任务的未决结果的 Future。该 Future 的 get 方法在成功完成时将会返回该任务的结果。
    <T> Future<T> submit(Callable<T> task);

    //提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。该 Future 的 get 方法在成功完成时将会返回给定的结果。
    <T> Future<T> submit(Runnable task, T result);

    //提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。该 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;

Executors工厂类

Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口。

public class Executors 

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

    public static ExecutorService newWorkStealingPool(int parallelism) 
        return new ForkJoinPool
            (parallelism,
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    

    public static ExecutorService newWorkStealingPool() 
        return new ForkJoinPool
            (Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    

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

    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));
    

    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);
    

    public static ScheduledExecutorService newSingleThreadScheduledExecutor() 
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
    

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 
        return new ScheduledThreadPoolExecutor(corePoolSize);
    

    public static ThreadFactory defaultThreadFactory() 
        return new DefaultThreadFactory();
    

    public static <T> Callable<T> callable(Runnable task, T result) 
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    

线程池分类

newCachedThreadPool():
    缓存型池子:
        先查看池中有没有以前建立的线程,如果有,就reuse。如果没有,就建一个新的线程加入池中。

    缓存型池子通常用于执行一些生存期很短的异步型任务。
    缺省timeout是60s,超过这个IDLE时长,线程实例将被终止及移出池。

    cache池线程数支持0-Integer.MAX_VALUE(显然完全没考虑主机的资源承受能力),60秒IDLE


newFixedThreadPool(int nThreads):
    任意时间点,最多只能有固定数目的活动线程存在。
    此时如果有新的线程要建立,只能放在另外的队列中等待,直到当前的线程中某个线程终止直接被移出池子。

    FixedThreadPool多数针对一些很稳定很固定的正规并发线程,多用于服务器


newScheduledThreadPool(int corePoolSize):
    调度型线程池
    这个池子里的线程可以按schedule依次delay执行,或周期执行

SingleThreadExecutor():
    单例线程,任意时间池中只能有一个线程
    用的是和cache池和fixed池相同的底层池,但线程数目是1,0秒IDLE(无IDLE)

以上是关于Executor ExecutorService Executors的主要内容,如果未能解决你的问题,请参考以下文章

Executor ExecutorService Executors

java Executor, ExecutorService, Executors 有什么不同

java并发编程框架 Executor ExecutorService invokeall

ExecutorService.submit()与Executor.execute()的区别

java多线程之Executor 与 ExecutorService两个基本接口

Java并发编程 - Executor,Executors,ExecutorService, CompletionServie,Future,Callable