咱們每個線程池都會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,判斷線程池裏的線程是否都處於工做狀態,若是沒有,則建立一個新的工做線程來執行任務。若是已經滿了,則已經飽和策略來處理這個任務。線程