线程池源码

Java并发工具类Executors详解
本文详细介绍了Java并发包下的工具类Executors,包括如何使用静态方法创建各种线程池,如固定线程数量、单一线程、具有缓存能力和定时任务的线程池。同时,深入探讨了ThreadPoolExecutor和ScheduledThreadPoolExecutor的内部实现机制。

Executors

Executors是concurrent包下的工具类,通过静态方法产生各种线程池

  1. 产生固定线程数量的线程池
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  1. 产生只有一个线程的线程池
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
  1. 产生具有缓存能力的线程池,如果任务数量超过能力,可回收利用空闲的线程
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  1. 产生具有定时任务或周期性任务的线程池
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

ThreadPoolExecutor

ThreadPoolExecutor是真正的线程池,构造方法有若干个参数

public ThreadPoolExecutor(
							  int corePoolSize, 
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
  1. corePoolSize:
    核心线程数,当前任务数量小于corePoolSize时,直接创建线程执行,当空闲时也不会被回收
  2. maximumPoolSize:
    最大线程数,当workQueue已满,并且maximumPoolSize>corePoolSize创建线程执行
  3. keepAliveTime:
    超过核心线程数量的线程的存活时间
  4. unit:
    超过核心线程数量的线程的存活时间的单位
  5. workQueue:
    任务等待队列
  6. threadFactory:
    线程工厂
  7. handler:
    异常处理策略,默认AbortPolicy,抛出异常

创建线程是调用addWorker方法,其核心是调用ThreadFactor产生一个线程

w = new Worker(firstTask);
final Thread t = w.thread;

private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
        final Thread thread;
        Runnable firstTask;
        volatile long completedTasks;

        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }
}

创建线程池如果不传入自定义线程工厂,会用默认的工厂

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

在defaultThreadFactory函数中直接new了一个线程

public Thread newThread(Runnable r) {
	Thread t = new Thread(group, r,namePrefix + threadNumber.getAndIncrement(), 0);
    return t;
}

ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor继承自ThreadPoolExecutor,队列用的是delayedWorkQueue

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

加入任务时,会加入到延迟队列中,如果任务到达时间,就执行,否则阻塞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值