/** * 源码里的注释实在是太清晰了,直接看源码吧 */ publicvoidexecute(Runnable command){ if (command == null) thrownew 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) { 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); elseif (workerCountOf(recheck) == 0) addWorker(null, false); } elseif (!addWorker(command, false)) reject(command); }
// Packing and unpacking ctl // 获取运行状态, c & 111_0{29} privatestaticintrunStateOf(int c){ return c & ~CAPACITY; } // 获取工作线程数 c & 000_1{29} privatestaticintworkerCountOf(int c){ return c & CAPACITY; } // 运行状态和工作线程数的组合 privatestaticintctlOf(int rs, int wc){ return rs | wc; }
/* * Bit field accessors that don't require unpacking ctl. * These depend on the bit layout and on workerCount being never negative. */ privatestaticbooleanrunStateLessThan(int c, int s){ return c < s; } privatestaticbooleanrunStateAtLeast(int c, int s){ return c >= s; } privatestaticbooleanisRunning(int c){ return c < SHUTDOWN; }