java之线程池面试题

面试官:线程池有哪些?分别的作用是什么?

常用的线程池有:

  1. newSingleThreadExecutor
  2. newFixedThreadExecutor
  3. newCacheThreadExecutor
  4. newScheduleThreadExecutor

1、newSingleThreadExecutor:

  单个线程的线程池,即线程池中每次只有一个线程工作,单线程串行执行任务;

2、newFixedThreadExecutor:

  固定数量的线程池,每提交一个任务就是一个线程,直到线程达到线程池的最大数量,然后后面进入等待队列直到前面的任务才继续执行;

3、newCacheThreadExecutor:

  可缓存线程池,当线程池大小超过了处理任务所需的线程,那么就会回收部分空闲(一般 是60秒无执行)的线程,当有任务时,会添加新线程来执行;

4、newScheduleThreadExecutor:

  大小无限制的 线程池,支持定时和周期性的执行线程。

ThreadPoolExecutor解说:

ThreadPoolExecutor是上面几个线程池底层的实现;

其中完整的构造方法是:

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
  • corePoolSize:线程池中所保存的线程数,包括空闲线程;
  • maximumPoolSize:线程池中允许的最大线程数;
  • keepAliveTime:线程存活时间,当超过keepAliveTime的时候后还无法获取新的任务,则返回null;
  • unit:keepAliveTime参数的时间单位;
  • workQueue:执行前用于保持任务的队列,此队列仅保持由execute方法提交的Runnable任务;
  • threadFactory:执行程序创建新线程时使用的工厂;
  • handler:由于超出线程范围和队列容量而使用执行被阻塞时所使用的处理策略;

猜你喜欢

转载自www.cnblogs.com/hujinshui/p/9961225.html