編輯:關於 Android 程式設計
本文分析 Gallery2 中 ThreadPool 的設計,以及應用啟動入口 GalleryAppImpl 與 Gallery 兩個類別的初始化流程。
先看成員變數 Executor mExecutor。
執行緒池的基本思想仍是物件池:預先開闢一塊空間存放多條(未死亡的)執行緒,池中執行緒的調度由池管理器負責。有任務進來就取一條執行,執行完後執行緒物件歸池而非銷毀。這樣可以反覆複用,避免頻繁建立與銷毀執行緒帶來的性能開銷。
用執行緒池管理的好處是保證系統穩定運行,特別適合執行緒數量龐大、工作量高的場景。假設要展示 1000 張圖片,若建立 1000 條執行緒去載入,系統必然崩潰;改用 5 條執行緒輪流執行,跑完的不回收而是等待下次調派,開銷就大幅下降了。
Executor 是 Java 的工具類,負責執行提交給它的 Runnable 任務。它提供了一種把任務提交與執行機制分離的方式——呼叫方只管提交,不必關心執行緒怎麼用、時序怎麼排。它通常用來取代手動建立執行緒。
Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2());
值得注意的是,Executor 介面並未要求執行必須是非同步的。最簡單的例子是直接在呼叫者執行緒中跑:
class DirectExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
更典型的是把任務丟到另一條執行緒:
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}
許多實作會依任務的提交方式與時序做分類。下面的 SerialExecutor 把提交的任務序列化後轉交給第二個 Executor,示範了一種組合式設計:
class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
final Executor executor;
Runnable active;
SerialExecutor(Executor executor) {
this.executor = executor;
}
public synchronized void execute(final Runnable r) {
tasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (active == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((active = tasks.poll()) != null) {
executor.execute(active);
}
}
}
邏輯是:執行 SerialExecutor 時先跑當前 Runnable 的 run(),完成後再從 tasks 佇列中取出下一個待執行的任務。
這個套件中提供的 Executor 實作都擴充了 ExecutorService 介面,而 ThreadPoolExecutor 提供了完整的執行緒池實作,Executors 類別則提供了一些便利的靜態工廠方法。
關於記憶體一致性:在把 Runnable 提交給 Executor 之前,提交執行緒中的寫入行為,對執行該任務的執行緒而言是可見的。
嚴格來說,Java 中執行緒池的頂級介面是 Executor,但它並不是一個執行緒池,只是一個執行線程的工具。真正的執行緒池介面是 ExecutorService。
依據實作的執行策略,execute() 可能在新執行緒中跑、在池中的某條執行緒上跑,也可能就在呼叫者執行緒中跑。ExecutorService 在 Executor 基礎上增加了兩個核心方法:
Future<?> submit(Runnable task) <T> Future<T> submit(Callable<T> task)
差異在於:Runnable 的 run() 沒有回傳值,Callable 的 call() 有回傳值。共同點是兩者都回傳 Future 物件,可以阻塞直到任務完成、取消任務,或檢查任務是否已結束。
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler);
各參數意義:corePoolSize 是池維持的最少執行緒數;maximumPoolSize 是最大執行緒數;keepAliveTime 與 unit 共同定義多餘執行緒的空閒存活時間;workQueue 是緩衝佇列;handler 是任務被拒絕時的處理策略。
當任務透過 execute() 送進來時,判定順序如下:
1. 若目前執行緒數小於 corePoolSize,即使現有執行緒都空閒,仍建立新執行緒處理。
2. 若執行緒數等於 corePoolSize 但佇列未滿,任務進入緩衝佇列。
3. 若執行緒數大於 corePoolSize、佇列已滿、且執行緒數小於 maximumPoolSize,建立新執行緒。
4. 若執行緒數已達 maximumPoolSize 且佇列已滿,交由 handler 的拒絕策略處理。
換句話說,處理優先序為:核心執行緒 → 任務佇列 → 最大執行緒 → 拒絕策略。
package threadpool.test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTestMain {
private static final int CORE_POOL_SIZE = 2;
private static final int MAX_POOL_SIZE = 4;
private static final int KEEP_ACTIVE_TIME = 3;
private static final int TASK_NUM = 10;
static public void main(String[] args) {
// 構造一個執行緒池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ACTIVE_TIME, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(3),
new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 1; i < TASK_NUM; i++) {
String name = "Task" + i;
System.out.println("ThreadPoolTestMain: put a task: " + name);
threadPool.execute(new ThreadPoolTask(name));
try {
Thread.sleep(20);
} catch (Exception err) {
err.printStackTrace();
}
}
}
}
package threadpool.test;
public class ThreadPoolTask implements Runnable {
private String mTaskName;
private static int CONSUME_SLEEP_TIME = 2000;
public ThreadPoolTask(String name) {
mTaskName = name;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
System.out.println("ThreadPoolTask :" + mTaskName);
try {
Thread.sleep(CONSUME_SLEEP_TIME);
} catch (Exception err) {
err.printStackTrace();
}
}
}
這裡刻意選了 DiscardOldestPolicy 作為拒絕策略,配合容量為 3 的佇列與 10 個任務,可以觀察到前面的任務被丟棄的行為。實際專案中該選哪種策略取決於業務語意:DiscardOldest 適合可丟棄舊請求的場景,CallerRunsPolicy 則能形成天然背壓。
GalleryAppImpl 在 AndroidManifest.xml 中註冊為 Application,應用建立時即被初始化,負責維護應用內部的全域資料。重點看兩個函數。
initializeAsyncTask()
private void initializeAsyncTask() {
// AsyncTask 類別需要在 UI 執行緒中載入,
// 所以在此處提前載入以符合該規則
try {
Class.forName(AsyncTask.class.getName());
} catch (ClassNotFoundException e) {
}
}
Class.forName() 會要求 JVM 搜尋並載入指定類別,也就是執行該類的靜態初始化區塊。AsyncTask 內部有一個 InternalHandler 綁在主執行緒的 Looper 上,必須在 UI 執行緒就完成類別載入,否則後續在子執行緒首次使用時會因為拿不到主 Looper 而拋出例外。這段程式碼就是為了迴避這個問題。
GalleryUtils.initialize()
public static void initialize(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
sPixelDensity = metrics.density;
Resources r = context.getResources();
TiledScreenNail.setPlaceholderColor(r.getColor(R.color.bitmap_screennail_placeholder));
initializeThumbnailSizes(metrics, r);
}
這裡把螢幕參數、WindowManager 與 Resource 都提前取出並快取成靜態欄位。 Gallery 是圖片密集型的應用,縮圖尺寸的計算依賴螢幕密度,提前算好可以避免每次捲動時重複計算。
onCreate 中由於 mStitchingProgressManager 賦值為 null,暫時未呼叫 getDataManager()。該函數主要用來管理 Gallery 的資料路徑層次。
從 launcher 進入圖庫會走到 Gallery.java,onCreate 中載入 main.xml:
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
if (savedInstanceState != null) {
getStateManager().restoreFromState(savedInstanceState);
} else {
initializeByIntent();
}
}
savedInstanceState 是 Activity 在 onPause 時保存的狀態,首次啟動時為 null。
initializeByIntent() 的分流邏輯
private void initializeByIntent() {
Intent intent = getIntent();
String action = intent.getAction();
if (Intent.ACTION_GET_CONTENT.equalsIgnoreCase(action)) {
startGetContent(intent);
} else if (Intent.ACTION_PICK.equalsIgnoreCase(action)) {
// 實際上並不支援 PICK,改按 GET_CONTENT 處理。
// 但需要先轉換 intent 中的 type
Log.w(TAG, "action PICK is not supported");
String type = Utils.ensureNotNull(intent.getType());
if (type.startsWith("vnd.android.cursor.dir/")) {
if (type.endsWith("/image")) intent.setType("image/*");
if (type.endsWith("/video")) intent.setType("video/*");
}
startGetContent(intent);
} else if (Intent.ACTION_VIEW.equalsIgnoreCase(action)
|| ACTION_REVIEW.equalsIgnoreCase(action)) {
startViewAction(intent);
} else {
startDefaultPage();
}
}
這個分流很值得參考:從桌面圖示進入會走 startDefaultPage;外部應用要選圖或檢視圖片,則分別走 startGetContent 與 startViewAction。PICK 這個已不建議使用的舊 action 被降級處理成 GET_CONTENT,並先把舊式的 vnd.android.cursor.dir/ 型別轉為現行寫法,是一種平滑的相容策略。
startDefaultPage()
public void startDefaultPage() {
PicasaSource.showSignInReminder(this);
Bundle data = new Bundle();
data.putString(AlbumSetPage.KEY_MEDIA_PATH,
getDataManager().getTopSetPath(DataManager.INCLUDE_ALL));
getStateManager().startState(AlbumSetPage.class, data);
mVersionCheckDialog = PicasaSource.getVersionCheckDialog(this);
if (mVersionCheckDialog != null) {
mVersionCheckDialog.setOnCancelListener(this);
}
}
data 中存放了相冊頂層路徑 /combo/{/mtp,/local/all,/picasa/all},也就是把 MTP 裝置、本機與 Picasa 雲端三個來源組合成一個虛擬根節點。Gallery2 的整個畫面架構建立在 StateManager 之上,每個畫面是一個 State 類別,這種設計讓返回堆疊與狀態保存的處理相當乾淨。
歡迎轉載與技術交流,轉載請標註出處:https://blog.csdn.net/discovery_by_joseph
源碼剖析(五):KeyboardFragment 打造文字與表情評論發表面板
說白了就是這個大家都很熟悉的功能: 這個功能牽扯到不少類別,我一個一個來拆解。 KeyboardFragment 類別 /** 底部帶 emotion 面板的文字和表
Android 設計模式:觀察者模式與下載進度更新
問題情境 在雜誌或檔案下載類應用中,常會遇到同一個下載任務需要同時更新多個 UI 位置的情況。例如同一本書在書店頁與書架頁都要顯示相同下載進度。若每個頁面各自輪詢,程式會
使用 MPAndroidChart 實作可旋轉餅圖
在需要呈現統計比例時,餅狀圖是常見選擇。若希望圖表更具互動性,可讓使用者透過觸控旋轉或查看不同扇區。本文以 MPAndroidChart 為例,說明如何在 Android
Codeforces 2B The Child and Set:lowbit 與位運算的入門課
這道題看起來是集合問題,骨子裡考的卻是二進位最低位——也就是 lowbit。 題目 Picks 有一個他最喜愛的集合,被孩子弄丟了。他記得關於集合 S 的兩件事: S