publicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler){ super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); // 调用父类的方法,先启动所有的核心线程 prestartAllCoreThreads(); } publicvoidexecute(Runnable command){ if (command == null) thrownew NullPointerException();
int c = ctl.get(); // 1. 如果工作线程数小于核心线程数(corePoolSize),则创建一个工作线程执行任务 if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); }
// 2. 如果当前是running状态,并且任务队列能够添加任务 if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get();
我们都知道,一个线程直接对应了一个 Thread 对象,在刚开始学习线程的时候我们也知道启动线程是通过 start () 方法,而并非 run () 方法。
那这是为什么呢?
如果你熟悉 Thread 的代码的话,你应该知道在这个类加载的时候会注册一些 native 方法
1 2 3 4 5 6 7 8 9
public classThreadimplementsRunnable{ /* Make sure registerNatives is the first thing <clinit> does. */ privatestaticnativevoidregisterNatives(); static { registerNatives(); } }