主執行緒啟動子執行緒查詢版本,Handler.handleMessage 收到訊息更新全域 newVersion,但主執行緒緊接著讀取仍為舊值。thread.join() 也無效。
Handler 預設綁定建立它的執行緒 (主執行緒 Looper)。handleMessage 實際在主執行緒稍後透過 Looper.loop() 執行,非同步於 thread.start()。thread.join() 僅等待子執行緒 run() 結束,不等待主執行緒訊息佇列處理。while (newVersion == null) {
try { Thread.sleep(100); } catch (InterruptedException ignored) {}
}
// 此時 newVersion 已更新
⚠️ 會凍結 UI,僅適用於啟動畫面等特定場景。
interface VersionCallback {
void onVersionReady(String version);
void onError();
}
// 子執行緒
new Thread(() -> {
String ver = checkVersionFromServer();
new Handler(Looper.getMainLooper()).post(() -> {
if (ver != null) callback.onVersionReady(ver);
else callback.onError();
});
}).start();
// 主執行緒實作介面
callback = new VersionCallback() {
@Override public void onVersionReady(String v) { newVersion = v; updateUI(); }
@Override public void onError() { showToast("檢查失敗"); }
};
// Coroutine
lifecycleScope.launch {
val version = withContext(Dispatchers.IO) { checkVersion() }
_newVersion.postValue(version) // LiveData 通知 UI
}
volatile 或 AtomicReference 保證可見性。