zoukankan      html  css  js  c++  java
  • Java高并发28-ThreadPoolExecutor原理剖析(2)

    线程池转换状态如下:

    • Running->Shutdown 显示调用shutdown()或隐式调用finalize()中的shutdown()
    • Running或者Shutdown->Stop 显示调用shutdownNow()
    • Shutdown->Tidying 当线程池和任务队列都是空的时候
    • Stop ->Tidying
    • Tidying -> Terminated

    线程池类型如下

    • newFixedThreadPool
      • 创建一个核心线程数和最大线程个数为都为nThreads的线程池,并且阻塞队列的最大长度为Integer.MAX_VALUE,keyAliveTime=0说明只要当前线程个数比核心线程个数多,并且是空闲的就可以回收
     public static ExecutorService newFixeThreadPool (int nThreads) {
      return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
     }
     
     public static ExecutorService newFixeThreadPool (int nThreads, ThreadFactory threadFactory) {
      return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
     }
    • newSingleThreadExecutor
    • 创建一个核心线程和最大线程个数都是1的线程池,并且阻塞队列长度为Integer.MAX_VALUE,keepAliveTime=0说明只要线程个数比核心线程个数多并且处于空闲状态就回收
     public static ExecutorService newSingleThreadExecutor() {
      return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(110L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));
     }
     
     // 使用自己的工厂
     public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
      return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(110L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()), threadFactory);
     }
    • newCachedThreadPool
    • 创建一个按需创建线程的线程池,初始线程个数为0,最大线程个数为Integer.MAX_VALUE,并且阻塞队列为同步队列,keepAliveTime=60,说明只要当前线程在60s内空闲则被回收,这个类型的特殊之处在于,加入同步队列的任务会被马上执行,同步队列里面最多只有一个任务.
     public static ExcecutorService newCachedThreadPool() {
      return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
     }
     
     // 使用自定义的线程工厂
     public static ExcecutorService newCachedThreadPool(ThreadFactory threadFactory) {
      return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
     }
  • 相关阅读:
    搭建james邮件服务器
    Spring -- AOP
    【RF库Collections测试】List Should Not Contain Duplicates
    【RF库Collections测试】Keep In Dictionary
    【RF库Collections测试】Insert Into List
    【RF库Collections测试】Get Index From List
    【RF库Collections测试】Get From List
    【RF库Collections测试】Count Values In List
    【RF库Collections测试】Get Slice From List
    【RF库Collections测试】Copy Dictionary
  • 原文地址:https://www.cnblogs.com/ruigege0000/p/15077722.html
Copyright © 2011-2022 走看看