java線程池中的Worker關鍵源碼

  1. 每個Worker主動去workQueue隊列裏取任務,如果取到任務了就執行
  2. 如果沒取到,得分以下幾種情況:
    • 線程池的線程數大於corePoolSize,非核心線程在等待keepAliveTime後關閉
    • 線程池的線程數小於corePoolSize時:
      • 如果設置了allowCoreThreadTimeOut = true,核心線程在等待keepAliveTime後,也會關閉
      • 如果沒有設置allowCoreThreadTimeOut(默認爲false),則核心線程阻塞,等待任務到來

注意:核心線程和非核心線程,只是語義上的說法,實際上沒有任何區別

Worker關鍵源碼

    private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
	
		// Worker主方法
		final void runWorker(Worker w) {
			Thread wt = Thread.currentThread();
			Runnable task = w.firstTask;
			w.firstTask = null;
			w.unlock(); // allow interrupts
			boolean completedAbruptly = true;
			try {
				// 關鍵代碼在於getTask()函數,當allowCoreThreadTimeOut = false && wc <= corePoolSize時,阻塞;否則等待keepAliveTime後返回null,循環結束
				while (task != null || (task = getTask()) != null) {
					w.lock();
					// If pool is stopping, ensure thread is interrupted;
					// if not, ensure thread is not interrupted.  This
					// requires a recheck in second case to deal with
					// shutdownNow race while clearing interrupt
					if ((runStateAtLeast(ctl.get(), STOP) ||
						 (Thread.interrupted() &&
						  runStateAtLeast(ctl.get(), STOP))) &&
						!wt.isInterrupted())
						wt.interrupt();
					try {
						beforeExecute(wt, task);
						Throwable thrown = null;
						try {
							task.run();
						} catch (RuntimeException x) {
							thrown = x; throw x;
						} catch (Error x) {
							thrown = x; throw x;
						} catch (Throwable x) {
							thrown = x; throw new Error(x);
						} finally {
							afterExecute(task, thrown);
						}
					} finally {
						task = null;
						w.completedTasks++;
						w.unlock();
					}
				}
				completedAbruptly = false;
			} finally {
				// 如果循環結束了,說明該Worker可以回收了
				processWorkerExit(w, completedAbruptly);
			}
		}
		
		
		private Runnable getTask() {
			boolean timedOut = false; // Did the last poll() time out?

			for (;;) {
				int c = ctl.get();
				int rs = runStateOf(c);

				// Check if queue empty only if necessary.
				if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
					decrementWorkerCount();
					return null;
				}

				int wc = workerCountOf(c);

				// Are workers subject to culling?
				boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

				if ((wc > maximumPoolSize || (timed && timedOut))
					&& (wc > 1 || workQueue.isEmpty())) {
					if (compareAndDecrementWorkerCount(c))
						return null;
					continue;
				}

				try {
					Runnable r = timed ?
						workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
						workQueue.take();
					if (r != null)
						return r;
					timedOut = true;
				} catch (InterruptedException retry) {
					timedOut = false;
				}
			}
		}
		
		private void processWorkerExit(Worker w, boolean completedAbruptly) {
			if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
				decrementWorkerCount();

			final ReentrantLock mainLock = this.mainLock;
			mainLock.lock();
			try {
				completedTaskCount += w.completedTasks;
				workers.remove(w);
			} finally {
				mainLock.unlock();
			}

			tryTerminate();

			int c = ctl.get();
			if (runStateLessThan(c, STOP)) {
				if (!completedAbruptly) {
					int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
					if (min == 0 && ! workQueue.isEmpty())
						min = 1;
					if (workerCountOf(c) >= min)
						return; // replacement not needed
				}
				addWorker(null, false);
			}
		}
		
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章