ScheduledThreadPoolExecutor杂乱笔记
java.util.concurrent.ScheduledThreadPoolExecutor public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { ... delayedExecute(t); return t; } private void delayedExecute(RunnableScheduledFuture<?> task) { ... super.getQueue().add(task); ... ensurePrestart(); ... } java.util.concurrent.ThreadPoolExecutor void ensurePrestart() { int wc = workerCountOf(ctl.get()); if (wc < corePoolSize) addWorker(null, true); else if (wc == 0) addWorker(null, false); } private boolean addWorker(Runnable firstTask, boolean core) { ... Worker w = null; try { w = new Worker(firstTask); final Thread t = w.thread; if (t != null) { ... t.start(); workerStarted = true; } } ... } java.util.concurrent.ThreadPoolExecutor.Worker private final class Worker extends AbstractQueuedSynchronizer implements Runnable Worker(Runnable firstTask) { ... // 1.Worker也是Runnable的子类 // 2.Runnable的子类run()方法执行逻辑 // 3.上面Thread t = w.thread; w.thread实际就是w自己 this.thread = getThreadFactory().newThread(this); } // java.util.concurrent.ThreadPoolExecutor#addWorker中t.start()之后调用Worker#run; // t.start()的t线程, 实际就是Worker的实例线程 java.util.concurrent.ThreadPoolExecutor.Worker#run public void run() { runWorker(this); } java.util.concurrent.ThreadPoolExecutor#runWorker final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; ... try { while (task != null || (task = getTask()) != null) { ... task.run(); ... } java.util.concurrent.ThreadPoolExecutor#getTask private Runnable getTask() { ... Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take(); ... } java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue#take public RunnableScheduledFuture<?> take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (;;) { RunnableScheduledFuture<?> first = queue[0]; if (first == null) available.await(); else { // 这里很重要,DelayedWorkQueue通过这个long delay判断是不是要调用task, for (;;)一直在自旋 long delay = first.getDelay(NANOSECONDS); if (delay <= 0) return finishPoll(first); ... } // task.run(); // 1. 执行scheduleWithFixedDelay方法传入的Runnable // 2.设置下一次的执行时间 // 3.重新建task放回到queue中 java.util.concurrent.ScheduledThreadPoolExecutor.ScheduledFutureTask#run public void run() { ... else if (ScheduledFutureTask.super.runAndReset()) { setNextRunTime(); reExecutePeriodic(outerTask); } }