咱们每个线程池都会nwe ThreadPoolExecutor类会引起几个参数
缓存
当有任务来以后,就会建立一个线程去执行任务,当线程池中的线程数量达到corePoolSize后,就会把到达的任务放到缓存当中最大的池中:线程池最大线程数量,它表示在线程池中最多能建立多少个线程;keepAliveTime:表示线程没有任务执行时最大保持多久时间会终止。app
因此咱们基本了解线程池的实现ide
corePoolSize与maximumPoolSize的区别:ui
corePoolSize :实际运用的线程数,maximumPoolSize :线程池最多建立多少个线程this
执行线程池源码实现就如咱们上面的讲解atom
/** * Executes the given task sometime in the future. The task * may execute in a new thread or in an existing pooled thread. * * If the task cannot be submitted for execution, either because this * executor has been shutdown or because its capacity has been reached, * the task is handled by the current {@code RejectedExecutionHandler}. * * @param command the task to execute * @throws RejectedExecutionException at discretion of * {@code RejectedExecutionHandler}, if the task * cannot be accepted for execution * @throws NullPointerException if {@code command} is null */ public void execute(Runnable command) { if (command == null) throw new 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); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); }
提交一个任务到线程池中,线程池的处理流程以下:spa
1,判断线程池里的核心线程是否在执行任务,若是不是(核心线程要么或者还有核心线程没有被建立)则建立一个新的工做线程来执行任务。若是核心线程都在执行任务,则进入下一个流程。2,线程池判断工做状态是否已满,若是工做类别没有满,则将新提交的任务存储在这个工做层次里。若是工做量满了,则进入下一个流程。3,判断线程池里的线程是否都处于工做状态,若是没有,则建立一个新的工做线程来执行任务。若是已经满了,则已经饱和策略来处理这个任务。线程