摘要:所以,并不代表線程池就一定立即就能退出,它也可能必須要等待所有正在執行的任務都執行完成了才能退出。
本文主要分析java.util.concurrent.ThreadPoolExecutor的實現原理,首先看它的構造函數:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueueworkQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
corePoolSize:線程池中穩定保存的線程數(一開始會小于這個數)
maximumPoolSize:線程池中最大線程數
keepAliveTime and unit:大于最小線程數的線程空閑后存活時間
workQueue:用于存放任務的阻塞隊列
threadFactory:用于創建線程的工廠類
handler:當任務隊列滿了且線程數達到了最大時的飽和策略
對于IO密集型任務,線程數一般設為CPU數*2,對于計算密集型任務,線程數一般設為CPU數。
當調用execute方法時:
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); }
其流程如圖:
創建線程是通過addWorker創建內部Worker類,其中調用getThreadFactory().newThread(this)來創建執行自己的線程,之后在addWorker中start該線程,執行Worker run方法中的runWorker會不斷的從任務隊列中獲取任務或阻塞,并且每次執行任務前會執行beforeExecute,之后會afterExecute,可以通過重寫beforeExecute方法來給執行線程重命名。
線程池狀態變化如圖:
RUNNING: Accept new tasks and process queued tasks
SHUTDOWN: Don"t accept new tasks, but process queued tasks
STOP: Don"t accept new tasks, don"t process queued tasks, and interrupt in-progress tasks
TIDYING: All tasks have terminated, workerCount is zero, the thread transitioning to state TIDYING will run the terminated() hook method
TERMINATED: terminated() has completed
shutdownNow終止線程的方法是通過調用Thread.interrupt()方法來實現的:
*If this thread is blocked in an invocation of the {@link * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link * Object#wait(long, int) wait(long, int)} methods of the {@link Object} * class, or of the {@link #join()}, {@link #join(long)}, {@link * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}, * methods of this class, then its interrupt status will be cleared and it * will receive an {@link InterruptedException}. * *
If this thread is blocked in an I/O operation upon an {@link * java.nio.channels.InterruptibleChannel InterruptibleChannel} * then the channel will be closed, the thread"s interrupt * status will be set, and the thread will receive a {@link * java.nio.channels.ClosedByInterruptException}. * *
If this thread is blocked in a {@link java.nio.channels.Selector} * then the thread"s interrupt status will be set and it will return * immediately from the selection operation, possibly with a non-zero * value, just as if the selector"s {@link * java.nio.channels.Selector#wakeup wakeup} method were invoked. * *
If none of the previous conditions hold then this thread"s interrupt * status will be set.
可以看到如果線程處于正常活動狀態,那么會將該線程的中斷標志設置為true,而無法中斷當前的線程。所以,shutdownNow并不代表線程池就一定立即就能退出,它也可能必須要等待所有正在執行的任務都執行完成了才能退出。
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/77876.html
摘要:一和并發包中的和主要解決的是線程的互斥和同步問題,這兩者的配合使用,相當于的使用。寫鎖與讀鎖之間互斥,一個線程在寫時,不允許讀操作。的注意事項不支持重入,即不可反復獲取同一把鎖。沒有返回值,也就是說無法獲取執行結果。 一、Lock 和 Condition Java 并發包中的 Lock 和 Condition 主要解決的是線程的互斥和同步問題,這兩者的配合使用,相當于 synchron...
摘要:比如上一篇文章提到的線程池的方法,它可以在線程池中運行一組任務,當其中任何一個任務完成時,方法便會停止阻塞并返回,同時也會取消其他任務。 當一個任務正在運行的過程中,而我們卻發現這個任務已經沒有必要繼續運行了,那么我們便產生了取消任務的需要。比如 上一篇文章 提到的線程池的 invokeAny 方法,它可以在線程池中運行一組任務,當其中任何一個任務完成時,invokeAny 方法便會停...
摘要:而且,線程池中的線程并沒有睡眠,而是進入了自旋狀態。普通的線程被中斷會導致線程繼續執行,從而方法運行完畢,線程退出。線程死亡超過時間,任務對列沒有數據而返回。線程死亡保證了線程池至少留下個線程。 線程在執行任務時,正常的情況是這樣的: Thread t=new Thread(new Runnable() { @Override ...
閱讀 3422·2023-04-25 22:44
閱讀 926·2021-11-15 11:37
閱讀 1632·2019-08-30 15:55
閱讀 2639·2019-08-30 15:54
閱讀 1080·2019-08-30 13:45
閱讀 1430·2019-08-29 17:14
閱讀 1853·2019-08-29 13:50
閱讀 3402·2019-08-26 11:39