线程池

常用的线程池 主要有:newCachedThreadPool;  newFixedThreadPool; newScheduledThreadPool;

不同的线程池设定了不同的构造形式;源码 如下;

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

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

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}


创建线程要调用 threadPoolExecutor();

summit 和execute 都可以提交线程,summit 会调用execute,所以可以认为 两者完成几乎一样的任务;

execute 具体执行

1.小于corepoolsize时,加worker;

2. core pool size 满时 check (double check )

防止如下的可能性的发生;

existing ones died since last checking) or the pool shut down since entry into this method

根据 结果 rollback 或者 enqueuing;

3.最后,连enqueue 时 fail,检查maximum pool size ,都无法添加,只能reject掉task了;


运行 task 可以 理解为 在线程池的线程中执行我们自己线程的runnable 线程;

忘记了重要的具体实现,线程池的runWorker,addWorker等 方法都用到了runState;

该字段保存了线程池的状态,定义了5种状态,如下;

// runState is stored in the high-order bits
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;


COUNT_BITS是Integer.MAXVALUE ;利用位运算也算是 一个节省空间的巧妙的方法吧;

今天 写到这;

如有不对,多多指点;



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值