线程池实现“线程复用”的原理

线程池实现“线程复用”的原理

在这里插入图片描述
ThreadPoolExecutor

	/**
	 * int corePoolSize 核心线程数
	 * int maximumPoolSize 线程池最大容量
	 * long 线程空闲时间,线程存活时间
	 * TimeUnit 时间单位
	 * threadFactory 线程工厂
	 * handler 执行拒绝策略对象
	 */
	ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
	        new ArrayBlockingQueue<>(1), new ThreadFactory() {
	    @Override
	    public Thread newThread(Runnable r) {
	        return null;
	    }
	}, new RejectedExecutionHandler() {
	    @Override
	    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
	
	    }
});

execute 方法

public void execute(Runnable command) {
	//首先会判断任务是否为空
    if (command == null)
        throw new NullPointerException();
    
    int c = ctl.get();
    /**
    * workerCountOf 当前使用的线程数
    * corePoolSize 核心线程数
    * workerCountOf < corePoolSize 那么加开线程
    */
    if (workerCountOf(c) < corePoolSize) {
    	//添加核心线程
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    /*
    * 当前线程数大于或等于核心线程
    * isRunning 判断线程池是否运行状态
    * 是运行状态那么把任务添加到队列中
    */
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        //线程停止运行 删除任务 并执行拒绝策略
        if (! isRunning(recheck) && remove(command))
            reject(command);
        //线程池在运行但是线程数为0 的时候需要添加新的线程
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    /**
    * 线程池不是running的状态
    * 线程数大于或等于核心线程数
    * 任务队列已经满了
    * 添加一个新的线程达到最大线程数为止
    * 达到最大线程数开始执行拒绝策略
    **/
    else if (!addWorker(command, false))
        reject(command);
}

addWorker 方法

private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (int c = ctl.get();;) {
            // Check if queue empty only if necessary.
            if (runStateAtLeast(c, SHUTDOWN)
                && (runStateAtLeast(c, STOP)
                    || firstTask != null
                    || workQueue.isEmpty()))
                return false;

            for (;;) {
                if (workerCountOf(c)
                    >= ((core ? corePoolSize : maximumPoolSize) & COUNT_MASK))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  // Re-read ctl
                if (runStateAtLeast(c, SHUTDOWN))
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        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 {
                    // Recheck while holding lock.
                    // Back out on ThreadFactory failure or if
                    // shut down before lock acquired.
                    int c = ctl.get();

                    if (isRunning(c) ||
                        (runStateLessThan(c, STOP) && firstTask == null)) {
                        if (t.getState() != Thread.State.NEW)
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        workerAdded = true;
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

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 {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    try {
                        task.run();
                        afterExecute(task, null);
                    } catch (Throwable ex) {
                        afterExecute(task, ex);
                        throw ex;
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值