編輯:關於 Android 程式設計
ScheduledThreadPoolExecutor 是一個支持定時任務與周期任務的線程池。如果讀過上一篇 Android Java 線程池 ThreadPoolExecutor 源碼篇,再來看這篇會輕鬆不少。
public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS, new DelayedWorkQueue()); }
先盯住兩個關鍵點:DelayedWorkQueue,以及放在這個隊列裡的 RunnableScheduledFuture(也就是 ScheduledFutureTask)。
我們重點看 offer、poll、take 三個方法。DelayedWorkQueue 以數組形式存放 RunnableScheduledFuture,而這個類實現了 Comparable 接口。每次 offer 時都會調用 siftUp 函數,依據 compareTo 的比較結果把元素插入隊列,並保證隊列始終按時間點從小到大有序——下標越小時間越早,下標越大時間越晚。poll 時則先從低位取出,再 siftDown 調整下標。而 compareTo 的比較依據,正是任務計算出來後要執行的時間點。

ScheduledFutureTask(Runnable r, V result, long triggerTime) { super(r, result); this.time = triggerTime; this.period = 0; this.sequenceNumber = sequencer.getAndIncrement(); } ScheduledFutureTask(Runnable r, V result, long triggerTime, long period) { super(r, result); this.time = triggerTime; this.period = period; this.sequenceNumber = sequencer.getAndIncrement(); }
接著看 getDelay、compareTo、isPeriodic、setNextRunTime 這幾個方法。
getDelay:邏輯很簡單,用 time 減去當前時間,用來判斷任務是否該執行了。
public long getDelay(TimeUnit unit) { return unit.convert(time - now(), NANOSECONDS); }
compareTo:比較的就是 time,任務入隊時用它來確定新任務該放在隊列哪個位置。
public int compareTo(Delayed other) { if (other == this) return 0; if (other instanceof ScheduledFutureTask) { ScheduledFutureTask x = (ScheduledFutureTask)other; long diff = time - x.time; if (diff < 0) return -1; else if (diff > 0) return 1; else if (sequenceNumber < x.sequenceNumber) return -1; else return 1; } long diff = getDelay(NANOSECONDS) - other.getDelay(NANOSECONDS); return (diff < 0) ? -1 : (diff > 0) ? 1 : 0; }
isPeriodic:判斷是否為周期任務。
public boolean isPeriodic() { return period != 0; }
setNextRunTime:周期任務第一次執行完後,用來推算下一次的執行時間,以此類推。period > 0 對應「上一個任務開始到下一個任務開始」(time += p,即 scheduleAtFixedRate);period < 0 對應「上一個任務結束到下一個任務開始」,即當前時間加上 (-p)(scheduleWithFixedDelay)。這個方法會在周期任務每次執行完後被調用。
private void setNextRunTime() { long p = period; if (p > 0) time += p; else time = triggerTime(-p); }
小結一下,為後面的分析做鋪墊:
1. offer 入隊時,會按任務的 time(執行時間)從小到大排序。
2. poll 出隊時,先取 index 0 上的任務(時間最早、最先執行),再調整隊列。
3. getDelay() 能得到當前任務還有多久執行。
4. setNextRunTime() 在周期任務執行一次後,算出下一次的執行時間,再重新放回隊列。
5. isPeriodic 判斷當前任務是否為周期任務,與第 4 點配合使用。
構造函數略過,直接看 submit。無論哪個 submit,最終都會走到 schedule 函數,我們直接看 schedule。
public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); RunnableScheduledFuture t = decorateTask(command, new ScheduledFutureTask(command, null, triggerTime(delay, unit))); delayedExecute(t); return t; } public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); if (period <= 0) throw new IllegalArgumentException(); ScheduledFutureTask sft = new ScheduledFutureTask(command, null, triggerTime(initialDelay, unit), unit.toNanos(period)); RunnableScheduledFuture t = decorateTask(command, sft); sft.outerTask = t; delayedExecute(t); return t; } public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); if (delay <= 0) throw new IllegalArgumentException(); ScheduledFutureTask sft = new ScheduledFutureTask(command, null, triggerTime(initialDelay, unit), unit.toNanos(-delay)); RunnableScheduledFuture t = decorateTask(command, sft); sft.outerTask = t; delayedExecute(t); return t; }
這幾個方法做的事情大同小異:先構造出 RunnableScheduledFuture(ScheduledFutureTask),再調用 delayedExecute(t)。每個方法裡都調用了 triggerTime(initialDelay, unit),用來根據延遲時間算出任務的執行時間。
scheduleAtFixedRate 和 scheduleWithFixedDelay 的區別主要在第三個參數:前者表示「上一個任務開始到下一個任務開始」的間隔,後者表示「上一個任務結束到下一個任務開始」的間隔。從代碼可以看出,scheduleAtFixedRate 傳給 period 的是大於 0 的值,scheduleWithFixedDelay 則是小於 0 的值,正好對應到 setNextRunTime() 的兩種分支。
接著看 delayedExecute:
private void delayedExecute(RunnableScheduledFuture task) { if (isShutdown()) reject(task); else { super.getQueue().add(task); if (isShutdown() && !canRunInCurrentRunState(task.isPeriodic()) && remove(task)) task.cancel(false); else ensurePrestart(); } }
第 5 行 super.getQueue().add(task); 會調用 DelayedWorkQueue 的 offer,前面說過,入隊時會按 time 從小到大排序。第 11 行的 ensurePrestart 內部調用了 addWorker,邏輯和上一篇 ThreadPoolExecutor 源碼篇裡完全一致。
void ensurePrestart() { int wc = workerCountOf(ctl.get()); if (wc < corePoolSize) addWorker(null, true); else if (wc == 0) addWorker(null, false); }
線程啟動後,接下來就是關心怎麼從隊列取任務,也就是 DelayedWorkQueue 的 take 和 poll。
public RunnableScheduledFuture take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (;;) { RunnableScheduledFuture first = queue[0]; if (first == null) available.await(); else { long delay = first.getDelay(NANOSECONDS); if (delay <= 0) return finishPoll(first); first = null; if (leader != null) available.await(); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { available.awaitNanos(delay); } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && queue[0] != null) available.signal(); lock.unlock(); } }
take 做的事就是拿到 index=0 的任務,取其 delay:若 delay <= 0,說明任務該執行了,直接 finishPoll 返回並做相應調整;否則就 available.await() 阻塞等待。
再看 poll,它和 take 差不多,區別在於帶了 timeout,不會一直阻塞。至於什麼時候走 poll、什麼時候走 take,可以參考上一篇 ThreadPoolExecutor 源碼篇。
public RunnableScheduledFuture poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (;;) { RunnableScheduledFuture first = queue[0]; if (first == null) { if (nanos <= 0) return null; else nanos = available.awaitNanos(nanos); } else { long delay = first.getDelay(NANOSECONDS); if (delay <= 0) return finishPoll(first); if (nanos <= 0) return null; first = null; if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { long timeLeft = available.awaitNanos(delay); nanos -= delay - timeLeft; } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && queue[0] != null) available.signal(); lock.unlock(); } }
最後看周期任務的執行邏輯,也就是 ScheduledFutureTask 的 run 方法。
public void run() { boolean periodic = isPeriodic(); if (!canRunInCurrentRunState(periodic)) cancel(false); else if (!periodic) ScheduledFutureTask.super.run(); else if (ScheduledFutureTask.super.runAndReset()) { setNextRunTime(); reExecutePeriodic(outerTask); } }
非周期任務直接調用 run,好理解。周期任務則先調用 runAndReset(),它會執行 Callable 的 call 方法跑完任務邏輯,再把任務狀態復位。第 8 行 setNextRunTime 計算下次執行時間;第 9 行 reExecutePeriodic 把任務重新塞回隊列。至此,周期任務的循環機制就完整了。
ScheduledThreadPoolExecutor 的隊列是 DelayedWorkQueue,offer 時按 delay 從小到大插入;poll 或 take 時都先取 index=0 的任務,再通過 getDelay 判斷是否到了執行時間。
隊列裡的任務是 ScheduledFutureTask,它實現了 Comparable 接口,在入隊時用到。關鍵方法有 getDelay、compareTo、isPeriodic、setNextRunTime。周期任務的執行機制是:每次執行完後重新計算下一次的運行時間,再插回隊列,這一切都在 ScheduledFutureTask 的 run 方法中完成。
public static ExecutorService newFixedThreadPool(int nThreads):固定 nThreads 個線程的線程池。任務數量少於 nThreads 時,線程會一個個開起來,達到 nThreads 後就一直存在。
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory):同上,但可以自定義線程工廠,更靈活。
public static ExecutorService newSingleThreadExecutor():只有一個線程的線程池。
public static ExecutorService newCachedThreadPool():不限制線程個數,線程空閒約 60 秒後會被關閉。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize):核心線程數為 corePoolSize 的周期線程池。
Executors 裡還有一些只是多傳入 ThreadFactory 或 RejectedExecutionHandler 的 static 方法,這裡就不一一列舉了。
Android 學習筆記(九):帶進度條的進度對話框實現
上一篇講了基礎的 ProgressDialog,這篇做一個更完整的例子:一個帶標題、圖標、水平進度條和確定/取消按鈕的「下載中」對話框,並用後台線程推進進度。 步驟一:
ContentProvider 完全指南:跨應用資料分享、UriMatcher 與單元測試實作
一、ContentProvider 基本概念 為了讓不同應用之間能安全地交換資料,Android 提供了 ContentProvider。它是跨應用資料交換的標準 API
自訂 ProgressBar:任何圖片都能變成轉圈動畫
今天群裡有人問怎麼自訂 Android Holo 主題下的 ProgressBar。剛好我之前做過類似的事——透過自寫動畫加上自訂 Style,可以用任何一張圖片當作 P
Android 入門實作(十九):用 SuperVideoPlayer 做一個能橫屏全螢幕的網路播放器
這一節來做一個實際的網路影片播放器。做法並非從零實作解碼與渲染,而是把 videoplayerlib 這個庫專案引入,再在外層 Activity 裡處理三件事:點擊開始播