线程池 原理学习笔记

 学习下线程池,也很好奇为什么线程为什么可以复用,本来还以为是线程状态之间的切换,这样还是会导致上下文切换,影响性能(上下文切换带来的性能和线程一直运行的性能怎么去权衡?)

参考博客:https://blog.csdn.net/Prepared/article/details/71616709(线程状态和上下文切换)

              https://blog.csdn.net/cjh94520/article/details/70545202/(复用原理定位)

               https://www.cnblogs.com/dolphin0520/p/3932921.html(实现细节)

 自己的理解,如有不正确,请给予指正

 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {//小于核心课程池
            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)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))//非核心线程池
            reject(command);
    }

  

 结合 newCachedThreadPool分析

构造 

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

corePoolSize=0;
maximumPoolSize=Integer.MAX_VALUE

keepAliveTime=60;
TimeUnit=s;
workQueue=SynchronousQueue;newCachedThreadPool
SynchronousQueue()队列只能容纳一个任务,因此如果瞬间存在有个线程的,一定会进入创建非核心线程池的队列,非核心线程池
 workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) ;超过时间得不到任务,线程就会被回收.




原文地址:https://www.cnblogs.com/jinjian91/p/9236622.html