Executor 框架简介

来源:互联网 发布:帝国cms图片替换地址 编辑:程序博客网 时间:2024/06/10 18:26

Executor 框架

  • Executor 框架
    • Executor 框架简介
    • Executors 创建线程池方法
      • newFixedThreadPool
      • newSingleThreadExecutor
      • newCachedThreadPool
      • newScheduledThreadPool
    • 更多
      • 通过 ThreadPoolExecutor类去 自定义线程池

Executor 框架简介

为了更好的控制多线程,JDK 提供了一套线程框架 Executor,帮助开发人员有限的进行线程控制,它们都在 java.util.concurrent包中,是 JDK 并发包的核心,其中有一个比较重要的类:Executors, 它扮演着线程工厂的角色,我们通过 Executors可以创建特定功能的线程池。

Executors 创建线程池方法

newFixedThreadPool()

newFixedThreadPool,该方法返回一个固定数量的线程池,该方法的线程数始终不变,当有一个任务提交时,若线程池中空闲,则立即执行,若没有,则会被缓存在一个任务队列中等待有空闲的线程去执行

newSingleThreadExecutor()

newSingleThreadExecutor,该方法会创建一个线程的线程池,若空闲则执行,若没有空闲线程,则缓存在任务队列中。

newCachedThreadPool()

newCachedThreadPool,返回一个可以根据实际情况调整线程个数的线程池,不限制最大的线程数量,若有空闲的线程,则执行任务,若无任务则不创建线程,并且每一个空闲线程会在60秒后自动回收

newScheduledThreadPool()

newScheduledThreadPool,返回一个SchededExecutorService对象,但该线程池可以指定线程的数量

更多

通过 ThreadPoolExecutor类去 自定义线程池

Executors工厂类无法满足我们的需求,我们可以自己去创建自定义的线程池,其实 Executors工厂类里面的创建线程方法内部都是采用 ThreadPoolExecutor类,这个类可以自定义线程,其构造方法如下

public ThreadPoolExecutor(    int corePoolSize,//核心线程数    int maximumPoolSize,//线程池的最大线程数    long keepAliveTime,//线程池里面的线程的存活时间    TimeUnit unit,// 时间单位    BlockingQueue<Runnable> workQueue,// 当线程池中没有空闲线程的时候, 存放任务的阻塞队列    ThreadFactory threadFactory,//    RejectedExecutlonHandler handler//当阻塞队列也满了的情况下,可以使用 这个处理者) {    ...}
public static ExecutorService newFixedThreadPool(int nThreads) {    return new ThreadPoolExecutor(nThreads, nThreads,                                  0L, TimeUnit.MILLISECONDS,                                  new LinkedBlockingQueue<Runnable>());}public static ExecutorService newSingleThreadExecutor() {    return new FinalizableDelegatedExecutorService        (new ThreadPoolExecutor(1, 1,                                0L, TimeUnit.MILLISECONDS,                                new LinkedBlockingQueue<Runnable>()));} public static ExecutorService newCachedThreadPool() {    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                  60L, TimeUnit.SECONDS,                                  new SynchronousQueue<Runnable>());}public ScheduledThreadPoolExecutor(int corePoolSize) {    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,          new DelayedWorkQueue());}