转载

Java线程池:简明易懂的源码分析

Java线程池:简明易懂的源码分析

Java线程池的一些基础知识,可以参考博客

Java线程池,你五分钟讲完,而我和面试官聊了半小时

本文将从源码角度分析线程池原理,加深对线程池原理的理解,简单背几个原理知识,其实很难得到面试官的青睐,了解源码知识,可以由内而外得征服面试官。

Java线程池状态转换

使用Integer类型(32bit) ctl高3位记录Java线程池的状态,低29位记录线程数量

RUNNING:111SHUTDOWN:000STOP:001

TIDYING:010TERMINATED:011.后面均又29位零

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3; // 29
//线程池最大容量2^29-1
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

private static final int RUNNING    = -1 << COUNT_BITS;
private static final int SHUTDOWN   =  0 << COUNT_BITS;
private static final int STOP       =  1 << COUNT_BITS;
private static final int TIDYING    =  2 << COUNT_BITS;
private static final int TERMINATED =  3 << COUNT_BITS;
//取得线程池运行状态
private static int runStateOf(int c)     { return c & ~CAPACITY; }
//取得线程池线程数量
private static int workerCountOf(int c)  { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }

下面从线程池的submit方法作为出发点,从源码角度分析,线程池的实现原理

submit方法

submit方法将提交的任务task,包装成RunnableFuture对象,既实现了Runnable接口,又实现了Future接口。之后会调用execute方法

public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Void> ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}

execute方法

当提交一个新任务,线程池的处理流程如下:

  • 判断线程池中核心线程数是否达到corePoolSize,若否,则创建一个新核心线程执行任务

  • 若核心线程数已达阈值,判断workQueue是否已满,若未满,则将新任务添加进阻塞队列

  • 若满,再判断,线程池中线程数是否达到阈值maximumPoolSize,若否,则新建一个非核心线程执行任务。若达到阈值,则执行线程池饱和策略

execute方法,各种参数

参数类型 用途
addWorker(firstTask, true) 创建核心线程,执行提交的任务
addWorker(firstTask, false) 创建非核心线程,执行提交的任务
addWorker(null, false) 创建非核心线程,执行工作队列中任务
addWorker(null, true) 创建核心线程,执行工作队列中任务
public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
        
    int c = ctl.get();
    //线程数小于corePoolSize
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    //线程数大于等于corePoolSize,尝试添加进workQueue
    if (isRunning(c) && workQueue.offer(command)) {
        //再次检查
        int recheck = ctl.get();
        //如果状态不为Running,则从队列中移除任务
        if (!isRunning(recheck) && remove(command))
            reject(command);
        //如果线程池数量为0,则添加一个非核心线程执行任务
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    //队列满,尝试新建非核心线程,执行任务
    else if (!addWorker(command, false))
        //否则执行拒绝策略
        reject(command);
}

addWorker方法

首先通过自旋操作,将线程总数加1.之后用独占锁锁住,构建一个Worker对象,将Worker对象添加进workers(HashSet<Worker>),释放锁,启动线程。

private boolean addWorker(Runnable firstTask, boolean core) {
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);
        //以下情况直接返回
	    //线程池处于STOP、TYDING、TERMINATED状态
        //线程池处于SHUTDOWN状态,firstTask!=null
        //线程池处于SHUTDOWN状态,firstTask==null, workQueue为空
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
               firstTask == null &&
               ! workQueue.isEmpty()))
            return false;
		//循环CAS操作,增加元素个数
        for (;;) {
            int wc = workerCountOf(c);
            if (wc >= CAPACITY ||
                wc >= (core ? corePoolSize : maximumPoolSize))
                return false;
            if (compareAndIncrementWorkerCount(c))
                break retry;
            //CAS失败,查看线程池状态是否改变,变化则跳到最外层循环
            c = ctl.get(); 
            if (runStateOf(c) != rs)
                continue retry;
        }
    }
    boolean workerStarted = false;
    boolean workerAdded = false;
    Worker w = null;
    try {
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
            final ReentrantLock mainLock = this.mainLock;
            //独占锁进行同步
            mainLock.lock();
            try {
                int rs = runStateOf(ctl.get());
			   //重新check一下线程池状态
                if (rs < SHUTDOWN ||
                    (rs == SHUTDOWN && firstTask == null)) {
                    if (t.isAlive()) 
                        throw new IllegalThreadStateException();
                    //添加任务
                    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;
}

Worker类( 实现了 AQS)

Worker对象,包括threadfirstTask成员变量。thread成员变量的构造函数的参数是自身的Worker对象。

所以调用thread成员变量的run方法,其实就是调用本身Worker对象的run方法

本身Worker对象的run方法,会调用runWorker方法,参数为本身Worker对象

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

    Worker(Runnable firstTask) {
        this.firstTask = firstTask;
        this.thread = getThreadFactory().newThread(this);
    }

    public void run() {
        runWorker(this);
    }
}

runWorker方法

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); //允许中断
    boolean completedAbruptly = true;
    try {
        //循环过程,执行完第一个任务后,一直从队列中拿取任务
        while (task != null || (task = getTask()) != null) {
            w.lock();
            //处于SHUTDOWN状态,并不会中断正在运行的任务
            if ((runStateAtLeast(ctl.get(), STOP) ||
                 (Thread.interrupted() &&
                  runStateAtLeast(ctl.get(), STOP))) &&
                !wt.isInterrupted())
                wt.interrupt();
            try {
                //执行任务前干一些事
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    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);
    }
}

getTask方法

从工作队列中,拿取任务,如果满足某几个条件(线程超时与否、线程池状态、工作队列是否为空),直接返回null.

private Runnable getTask() {
    boolean timedOut = false; 
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        //线程池状态为SHUTDOWN,并且workQueue为空
        //线程池处于STOP、TYDING、TERMINATED状态
        //以上两种情况,返回null
        if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
            //线程总数减一
            decrementWorkerCount();
            return null;
        }
        int wc = workerCountOf(c);
        //allowCoreThreadTimeOut为true,运行核心线程受超时机制影响
        boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
		
        //空闲线程超时,直接返回null
        if ((wc > maximumPoolSize || (timed && timedOut))
            && (wc > 1 || workQueue.isEmpty())) {
            if (compareAndDecrementWorkerCount(c))
                return null;
            continue;
        }

        try {
            //从队列中取任务
            //如果空闲线程超时,workQueue.poll方法返回null
            Runnable r = timed ?
                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}

参考文章

Java线程池源码分析(一)

Java 线程池 ThreadPoolExecutor 源码分析

正文到此结束
本文目录