JAVA线程池有哪些配置参数,各自的作用是什么?


一、重要参数

corePollSize:核心线程数。在创建了线程池后,线程中没有任何线程,等到有任务到来时才创建线程去执行任务。
maximumPoolSize:最大线程数。表明线程中最多能够创建的线程数量。
keepAliveTime:空闲的线程保留的时间。
TimeUnit:空闲线程的保留时间单位。
BlockingQueue:阻塞队列,存储等待执行的任务。参数有ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue可选。
ThreadFactory:线程工厂,用来创建线程
RejectedExecutionHandler:队列已满,而且任务量大于最大线程的异常处理策略。
  ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
  ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
  ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
  ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务
 

二、四类构造函数

1、 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
2、ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
3、 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
4、 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)

三、实现线程池的四种策略

1、newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer. MAX_VALUE,
                                      60L, TimeUnit.  SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
 
2、newFixedThreadPool
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.  MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
 
3、newSingleThreadExecutor
 public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            ( new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.  MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
 
4、newScheduledThreadPool
   public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    public ScheduledThreadPoolExecutor( int corePoolSize) {
        super(corePoolSize, Integer. MAX_VALUE, 0, TimeUnit. NANOSECONDS,
              new DelayedWorkQueue());
    }
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM