Worker extends AbstractQueuedSynchronizer队萤, 它就是一個運行task的線程,沒有task就去queue里去take茧妒,它繼承AQS是
/** * Class Worker mainly maintains interrupt control state for * threads running tasks, along with other minor bookkeeping. * This class opportunistically extends AbstractQueuedSynchronizer * to simplify acquiring and releasing a lock surrounding each * task execution. This protects against interrupts that are * intended to wake up a worker thread waiting for a task from * instead interrupting a task being run. We implement a simple * non-reentrant mutual exclusion lock rather than use * ReentrantLock because we do not want worker tasks to be able to * reacquire the lock when they invoke pool control methods like * setCorePoolSize. Additionally, to suppress interrupts until * the thread actually starts running tasks, we initialize lock * state to a negative value, and clear it upon start (in * runWorker). */
英文不怎么會身笤,大概就是保護線程運行task,初始的時候置state為-1.
想了半天斤彼,得出:
1分瘦, 如果此線程運行task不去拿個排它鎖,此時如果出現(xiàn)清理idel線程的行為琉苇,方法?interruptIdleWorkers 就不用這行:
if (!t.isInterrupted() && w.tryLock()) {
如果task代碼實現(xiàn)里有Thread.sleep或者join等嘲玫,那就會被中斷,task運行沒完成并扇。這個應(yīng)該就是注釋里所說避免
"instead interrupting a task being run"的含義去团。加鎖以后線程池shutdown或者resetsize需要interrupt threads需要先
拿到鎖。
2穷蛹, 有人問為啥不直接用ReentrantLock土陪,這個回答也是解釋代碼注釋。
https://stackoverflow.com/questions/42189195/why-threadpoolexecutorworker-extends-abstractqueuedsynchronizer
很奇怪怎么thread自己怎么會有分身術(shù)肴熏,在專注與運行task的時候怎么會去調(diào)用setCorePoolSize呢鬼雀?
protected void beforeExecute(Thread t, Runnable r) { }
這方法在ThreadPoolExecutor里, 可以重寫蛙吏, 它在task.run 之前被調(diào)用源哩,故還是有這種機會的。afterExecute同理鸦做。