Executor、Executors、ExecutorService实现异步操作

 

Executor:一个接口,定义了一个接受Runnable对象的方法executor,它用来执行一个任务,即执行一个实现了Runnable接口的类 ,executor.execute(new RunnableTask());

ExecutorService:是一个比Executor使用更广泛的子类接口,它继承Executor接口,提供管理进程终止的方法和可以生成Future的方法,用于跟踪一个或者多个异步任务的进度。它提供了两种不同的方法来关闭ExecutorService,拒绝新的任务,这两种方法就是shutdown()和shutdownNow(),shutdown()方法允许之前已经提交的任务执行完毕之后再挂起关闭,shutdownNow()方法则阻止正在等待的任务启动,并尝试停止之前正在执行的任务。通过ExecutorService中的submit()方法可以返回Future对象,可以调用isDone()方法查询Future是否已完成,当任务完成时,它具有一个结果,可以通过get()方法获取到该结果,Future提供了cancel()方法用来取消执行pending中的任务。

ExecutorService executroService = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

executorService.execute(ew RunnableTask());

new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)

corePoolSize:线程池中所保存的核心线程数,包括空闲线程;

maximumPoolSize:池中允许的最大线程数;

keepAliveTime:线程池中的空闲线程所能持续的最长时间;

unit:持续时间的单位;

workQueue:任务执行前保存任务的队列,仅保存由execute方法提交的Runnable任务。

当试图通过execute方法将一个Runnable任务添加到线程池中时:

(1)如果线程池中线程的数量小于corePoolSize,即使线程池中有空闲的线程,也会创建一个新的线程来执行新添加的任务;

(2)如果线程池中线程数量大于等于corePoolSize,但缓存队列中workQueue未满,则将新添加的任务放到workQueue中,按照FIFO的原则依次等待执行。

(3)如果线程池中线程数量大于等于corePoolSize,并且缓存队列中WorkQueue已满,但线程池中线程数量小于maximumPoolSize,则会创建新的线程来处理添加的任务。

(4)如果线程池中线程数量等于maximumPoolSize,那么通过handler所指定的策略来处理此任务。

为什么用Executor而不用new Thread呢

(1)每次我们new Thread都会创建一个对象,不能被重用,而且对象的创建和销毁是消耗资源的;

(2)使用new Thread无法设置定时、线程中断等功能;

(3)new Thread缺乏统一的管理,new多了就会出现线程之间的竞争,或者占用过多的cpu资源,甚至可能导致死机;

四种线程池:

java通过Executors类提供四种线程池:

(1)newCachedThreadPool线程池

 /**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available.  These pools will typically improve the performance
     * of programs that execute many short-lived asynchronous tasks.
     * Calls to {@code execute} will reuse previously constructed
     * threads if available. If no existing thread is available, a new
     * thread will be created and added to the pool. Threads that have
     * not been used for sixty seconds are terminated and removed from
     * the cache. Thus, a pool that remains idle for long enough will
     * not consume any resources. Note that pools with similar
     * properties but different details (for example, timeout parameters)
     * may be created using {@link ThreadPoolExecutor} constructors.
     *
     * @return the newly created thread pool
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

它将corePoolSize设定为0,而将maximumPoolSize设定为了Integer的最大值,线程空闲超过60秒,将会从线程池中移除。由于核心线程数为0,因此每次添加任务,都会先从线程池中找空闲线程,如果没有就会创建一个线程(SynchronousQueue<Runnalbe>决定的,后面会说)来执行新的任务,并将该线程加入到线程池中,而最大允许的线程数为Integer的最大值,因此这个线程池理论上可以不断扩大。
(2)newFixedThreadPool线程池

 /**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue.  At any point, at most
     * {@code nThreads} threads will be active processing tasks.
     * If additional tasks are submitted when all threads are active,
     * they will wait in the queue until a thread is available.
     * If any thread terminates due to a failure during execution
     * prior to shutdown, a new one will take its place if needed to
     * execute subsequent tasks.  The threads in the pool will exist
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @return the newly created thread pool
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

newFixedThreadPool线程池是创建一个固定值的线程池,keepAliveTime设定为了0,也就是说线程只要空闲下来,就会被移除线程池。如果业务超过线程数量,需要排队,谁的线程结束了就直接拿过来使用,如果线程充足,就会创建新的线程。

(3)newSingleThreadExecutor线程池

  /**
     * Creates an Executor that uses a single worker thread operating
     * off an unbounded queue. (Note however that if this single
     * thread terminates due to a failure during execution prior to
     * shutdown, a new one will take its place if needed to execute
     * subsequent tasks.)  Tasks are guaranteed to execute
     * sequentially, and no more than one task will be active at any
     * given time. Unlike the otherwise equivalent
     * {@code newFixedThreadPool(1)} the returned executor is
     * guaranteed not to be reconfigurable to use additional threads.
     *
     * @return the newly created single-threaded Executor
     */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

newSingleThreadExecutor是一个单线程的线程池,它所有的任务都是用这个线程来执行的,保证所有任务按照指定顺序执行,还能保证当一个线程发生异常时,它会继续往下执行。

(4)newScheduledThreadPool 

/**
     * Creates a thread pool that can schedule commands to run after a
     * given delay, or to execute periodically.
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle
     * @return a newly created scheduled thread pool
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

创建一个定长线程池,支持定时及周期性任务执行。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值