线程池

来源:互联网 发布:js仿ios日期选择器 编辑:程序博客网 时间:2024/06/06 06:56

常用的线程池 主要有: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 bitsprivate 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 ;利用位运算也算是 一个节省空间的巧妙的方法吧;

今天 写到这;

如有不对,多多指点;