java中线程执行器基本知识

ThreadPoolExecutor:  new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);

corePoolSize:除非设置了allowCoreThreadTimeOut,否则即使它们处于空闲状态,也要保留在池中的线程数。

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

keepAliveTime:当线程数大于核心时,这是多余空闲线程在终止之前等待新任务的最长时间。就是设置空闲时间。如果为0表示不等待直接移除

unit:keepAliveTime的时间单位

keepAliveTime:在执行任务之前用于保存任务的队列。 此队列将仅保存execute方法提交的Runnable任务。

如果当前线程数小于corePoolSize 首先使用给定命令启动一个新线程任务。当前线程数大于等于corePoolSize,如果任务可以成功排队,不开启新的线程。如果排队失败就会创建新的线程,不能大于maximumPoolSize。

一般workQueue 正常情况下都比较大,如果想测试当前线程池的数量大于corePoolSize 请把workQueue的队列数调小,这样就能看到效果了。

  Executors.newFixedThreadPool(nThreads):nThreads 线程数量

代码

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

可以看出 maximumPoolSize和maximumPoolSize 相等 所以会创建出固定的线程池数量。

 Executors.newCachedThreadPool();

代码

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

默认线程数量是0 最大线程数为Integer的最大值,线程空闲时间为60秒。

Executors.newScheduledThreadPool(corePoolSize):corePoolSize 线程数量

 public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

空闲时间设置为0表示线程已空闲就进行清除,并且这里使用的DelayedWorkQueue。

Executors.newSingleThreadExecutor();

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

corePoolSize 和maximumPoolSize 相等,都是1 所以里面的线程只有一个。

其他方法:

shutdwon():等待已经运行的线程运行完。

shutdownNow() :不管线程是否执行完,立即关闭。

可以覆盖beforeExecute 和afterExecute 方法 执行我们需要的代码。
    

猜你喜欢

转载自blog.csdn.net/hyhanyu/article/details/81239256