线程池及部分源码小结

线程的简单概念

线程是CPU调度的最小单位,属于进程的一部分,线程间共享所在进程的资源,线程模型有KLT和ULT两种,Java中采用的是KLT模型,也就是说Java中每创建一个线程会同步的在OS中创建一个线程
扩展:协程
协程和线程的不同之处在于切换时不会发生上下文的切换,而是通过还原保存的栈信息来实现协程之间的切换

线程池的简单理解

线程池顾名思义就是由多个线程组成的池子,在需要使用多线程的场景下我们可以使用线程池
为什么要用线程池而不是一个个的创建线程呢,因为每次创建线程时都需要消耗资源和时间,为了更高效的使用线程,引入了线程池的概念,对线程统一分配、监控和调优
线程池可以复用线程,减少线程创建和销毁的消耗,提高性能,在需要线程时直接使用现有的线程从而提高响应速度,可以对线程进行管理和优化

线程池的状态

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
线程池的状态记录在ctl变量的高三位中,一共有5种状态,分别为RUNNING、SHUTDOWN、STOP、TIDYING、TERMINATED
RUNNING:可以接收新任务并处理已添加任务,也是线程池的初始状态
SHUTDOWN:不接收新任务但能处理已添加的任务
STOP:不接收新任务,不处理已添加任务,中断正在处理的任务
TIDYING:所有任务已终止,ctl记录的任务数量为0时处于此状态
TERMINATED:线程池彻底终止

线程池的参数

	public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
corePoolSize:核心线程数,每次提交任务时,线程池就创建一个线程执行任务直到创建的线程数等于corePoolSize
继续提交的任务放进阻塞队列等待执行,如果调用了prestartAllCoreThreads()方法会提前创建启动所有核心线程
maximumPoolSize:线程池中的最大线程数,当阻塞队列已满并且当前线程数小于maximunPoolSize,则创建新线程执行任务
keepAliveTime:非核心线程的存活时间,非核心线程空闲时经过多长时间销毁
unit:存活时间的单位
workQueue:阻塞队列,JDK提供了4种阻塞队列
	ArrayBlockingQueue:基于数组的有界阻塞队列
	LinkedBlockingQueue:基于链表的阻塞队列
	SynchronousQueue:不存储元素的阻塞队列,每次插入元素之前必须等另外一个线程调用移除操作,否则插入线程一直阻塞
	priorityBlockingQueue:具有优先级的无界阻塞队列
threadFactory:创建线程的线程工厂,使用自定义的threadFactory可以定义线程的名称
handler:拒绝策略,当阻塞队列已满且无法创建新线程处理时的策略,线程池提供了4种策略
	AbortPolicy:默认的策略,直接抛出异常
	CallerRunsPolicy:返回给调用线程执行任务
	DiscardOldestPolicy:丢弃等待最久的任务,即最早进入队列的任务,并执行当前任务
	DiscardPolicy:直接丢弃任务

线程池的一些监控方法

	//获取线程池中的任务总数
	long taskCount = executor.getTaskCount();
	//获取已完成的任务数
	long completedTaskCount = executor.getCompletedTaskCount();
	//获取当前线程池中的线程数
	int poolSize = executor.getPoolSize();
	//获取当前线程池中已正在执行任务的线程数
	int activeCount = executor.getActiveCount();

线程池的工作流程

简单来说,创建好一个线程池后,向线程池提交任务时,线程池首先判断当前池里的线程数是否小于corePoolSize
如果小于则创建一个线程来执行任务,直到线程的个数达到corePoolSize为止,再提交的任务就放到阻塞队列里,等待
线程池里的线程从队列中取任务执行,如果阻塞队列塞满了,线程池就判断现在存在的线程数是否小于maximumPoolSize,
如果小于则创建新线程执行任务,超过corePoolSize的线程叫做非核心线程,如果不小于则采取预设的拒绝策略处理任务

部分源码分析

	public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
        	//如果当前线程数小于corePoolSize,新建线程执行任务
        	//addWorker的第二个参数的含义是线程上限是根据corePoolSize(true)还是maximumPoolSize(false)来判断
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
        	//线程池正在运行,任务添加到队列
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
            	//线程池已经停止运行,将任务从队列中移除,拒绝该任务
                reject(command);
            else if (workerCountOf(recheck) == 0)
            	//当前线程数为0,新建一个线程
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
	        //当前线程数不小于corePoolSize,并且添加阻塞队列失败
	        //新建线程失败,执行拒绝策略
            reject(command);
    }
	
	//创建线程执行任务的方法
	private boolean addWorker(Runnable firstTask, boolean core) {
        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 {
        	//将firstTask封装为worker
            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();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                	//启动线程,调用work中的run方法
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }
	
	//执行任务的方法
	final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
        	//如果task为null,调用getTask方法获取任务
            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);
                    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);
        }
    }
	
	//获取任务的接口
	private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);
			
			//timed变量用于超时控制,allowCoreThreadTimeOut默认是false
			//核心线程不超时,非核心线程会超时
            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值