Java线程池流程及源码简析

一、为何要使用线程池

// 创建并开启线程
Thread t = new Thread(){
    @Override
    public void run() {

    }
};
t.start();

// 使用单线程线程池
ExecutorService service = Executors.newSingleThreadExecutor();
// 往线程池里添加任务
service.execute(new Runnable() {
    @Override
    public void run() {

    }
});

线程池主要解决了两个问题:

  1. 频繁创建销毁线程的开销
  2. 任务的管理
    在异步任务比较多时,创建、销毁线程会占用很多系统资源;这时候,使用线程池,就可以实现线程的复用,让人专注于任务的实现,而不是管理线程。

二、线程池简介

1、什么是线程池

线程池(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:线程池中核心线程的数量
maxinumPoolSize:线程池中最大允许多少个线程
keepAliveTime:普通线程存活时间
workQueue:任务队列

2、线程池分类

(1)SingleThreadExecutor单线程的线程池

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

核心线程数为1,最大线程数为1,也就是说SingleThreadExecutor这个线程池中的线程数固定为1。使用场景:当多个任务都需要访问同一个资源的时候,排队。
(2)FixedThreadExecutor固定容量的线程池

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

核心线程数为n,最大线程数为n。使用场景:明确同时执行任务数量时。
(3)CachedThreadExecutor可缓存的线程池

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                              60L, TimeUnit.SECONDS,
                              new SynchronousQueue<Runnable>());

核心线程数为0,最大线程数无上限,线程超时时间60秒。使用场景:处理大量耗时较短的任务。
(4)ScheduledThreadExecutor执行定时任务的线程池

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public class ScheduledThreadPoolExecutor
        extends ThreadPoolExecutor
        implements ScheduledExecutorService {
        public ScheduledThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize, Integer.MAX_VALUE,
                  DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
                  new DelayedWorkQueue());
        }    
}

核心线程数自定,最大线程数无上限。使用场景:处理延时任务。

3、线程池工作流程

(1)添加任务
3.1.1 如果线程池中,运行的线程数少于核心线程数(corePoolSize),那么就新建一个核心线程,并执行该任务。
3.1.2 如果线程池中,运行的线程数大于等于corePoolSize,将任务添加到待执行队列中(workQueue),等待执行。
3.1.3 如果上面的情况添加到队列失败,那么就新建一个非核心线程,并在该线程执行该任务。
3.1.4 如果上面的情况添加到队列失败,新建一个非核心线程的时候发现已经达到最大值,建不了,这个时候机会拒绝执行这个任务,即ThreadPoolExecutor构造函数里的RejectedExecutionHandler会被调用
8888.png

(2)任务队列是如何执行的?
每一个工作线程必然是被一个任务唤醒的,这个任务被称作初始任务(firstTask)。当一个工作线程完了它的初始任务之后,会从待执行的任务队列(workQueue)中取新的任务。对于一个设置了超时时间的普通线程,如果在指定的时间之后仍然没有新任务到达,那么这个线程就会停止等待任务并且销毁。

ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(new Runnable() {
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("线程:" + threadName + "开始了");
        try {
            Thread.sleep(30000);
        } catch (Exception e){
        }
        System.out.println("线程:" + threadName + "结束了");
    }
});
service.execute(new Runnable() {
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("线程:" + threadName + "开始了");
        try {
            Thread.sleep(20000);
        } catch (Exception e){
        }
        System.out.println("线程:" + threadName + "结束了");
    }
});
service.execute(new Runnable() {
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("第二轮A线程:" + threadName + "开始了");
        try {
            Thread.sleep(20000);
        } catch (Exception e){
        }
        System.out.println("第二轮A线程:" + threadName + "结束了");
    }
});
service.execute(new Runnable() {
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("第二轮B线程:" + threadName + "开始了");
        try {
            Thread.sleep(20000);
        } catch (Exception e){
        }
        System.out.println("第二轮B线程:" + threadName + "结束了");
    }
});
线程:pool-1-thread-1开始了
线程:pool-1-thread-2开始了
线程:pool-1-thread-2结束了
第二轮A线程:pool-1-thread-2开始了
线程:pool-1-thread-1结束了
第二轮B线程:pool-1-thread-1开始了
第二轮A线程:pool-1-thread-2结束了
第二轮B线程:pool-1-thread-1结束了

三、线程池源码分析

/**
* ThreadPoolExecutor类的execute方法
* 添加一个任务
*/
public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    int c = ctl.get();
    // 当前线程数量小于核心线程数
    if (workerCountOf(c) < corePoolSize) {
        // 调用addWorker方法
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    // 添加任务到任务队列workQueue
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command);
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    else if (!addWorker(command, false))
        reject(command);
}
/**
* ThreadPoolExecutor类的addWorker方法
*/
private boolean addWorker(Runnable firstTask, boolean core) {
    // 判断一个runnable是否符合添加的条件
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
               firstTask == null &&
               ! workQueue.isEmpty()))
            return false;

        for (;;) {
            int wc = workerCountOf(c);
            if (wc >= CAPACITY ||
                wc >= (core ? corePoolSize : maximumPoolSize))
                return false;
            if (compareAndIncrementWorkerCount(c))
                break retry;
            c = ctl.get();  // Re-read ctl
            if (runStateOf(c) != rs)
                continue retry;
            // else CAS failed due to workerCount change; retry inner loop
        }
    }

    boolean workerStarted = false;
    boolean workerAdded = false;
    Worker w = null;
    try {
        // 创建一个Worker,那么worker是什么呢,请看下面的源码
        // 实际上Worker就是一个Runnable,里面封装了一个thread
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                // Recheck while holding lock.
                // Back out on ThreadFactory failure or if
                // shut down before lock acquired.
                int rs = runStateOf(ctl.get());

                if (rs < SHUTDOWN ||
                    (rs == SHUTDOWN && firstTask == null)) {
                    if (t.isAlive()) // precheck that t is startable
                        throw new IllegalThreadStateException();
                    // 把Worker添加到HashSet里
                    workers.add(w);
                    int s = workers.size();
                    if (s > largestPoolSize)
                        largestPoolSize = s;
                    workerAdded = true;
                }
            } finally {
                mainLock.unlock();
            }
            if (workerAdded) {
                // 开启线程
                t.start();
                workerStarted = true;
            }
        }
    } finally {
        if (! workerStarted)
            addWorkerFailed(w);
    }
    return workerStarted;
}
/**
* ThreadPoolExecutor类的内部类Worker类
*/
private final class Worker
    extends AbstractQueuedSynchronizer
    implements Runnable
{
    final Thread thread;
    /** Initial task to run.  Possibly null. */
    Runnable firstTask;

    /**
     * Creates with given first task and thread from ThreadFactory.
     * @param firstTask the first task (null if none)
     */
    Worker(Runnable firstTask) {
        setState(-1); // inhibit interrupts until runWorker
        this.firstTask = firstTask;
        // 创建一个Thread,传进去的当前对象,所以thread.start()
        // 会调用Worker的run方法
        this.thread = getThreadFactory().newThread(this);
    }

    /** Delegates main run loop to outer runWorker. */
    public void run() {
        // 最终会调用runWorker方法
        runWorker(this);
    }
}
/**
* ThreadPoolExecutor类的的runWorker方法
*/
final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        // 如果第一次进来,即firstTask!=null,所以直接进到里面调用run方法
        // 如果不是第一次进来,那么就需要从getTask()里获取任务
        // 这里分两种情况,这个线程执行完任务后,getTask没有任务了,那么这个
        // 线程就终止了。如果还有任务,那么就会继续执行对应的任务。
        while (task != null || (task = getTask()) != null) {
            w.lock();
            try {
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    // 执行调用者的run方法
                    task.run();
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}
/**
* ThreadPoolExecutor类的的getTask方法
*/
private Runnable getTask() {
    boolean timedOut = false; // Did the last poll() time out?
    for (;;) {
        try {
            // 获取任务队列workQueue里的任务
            // 任务队列里的任务是在execute方法里,workQueue.offer加入的
            Runnable r = timed ?
                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}

举个例子,假设我们创建了一个单线程的线程池,这个时候我们通过excute添加任务1,由于当前线程小于核心线程数1,所以就会调用addWorker方法,最终调用runWorker方法执行任务1里的代码,任务1里的代码还在执行中时,我们继续通过excute添加任务2,这个时候由于当前线程大于等于核心线程数1,所以会调用workQueue.offer添加到任务队列里等待。等任务1里的代码执行完后,会调用getTask,这个时候发现getTask里有任务2,那么接着就会继续执行任务2里的代码。
另外一种情况是,任务1里的代码执行完成后,我们再通过excute添加任务2,由于这个时候任务1的线程已经执行完毕,所以它已经中止退出了,这个时候去判断当前线程即会发现是小于核心线程数1的,所以继续重复上面的调用addWorker方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值