編輯:Android 程式設計入門
我曾經對 Thread 和 Runnable 有個錯誤理解:以為用了 Runnable 就開了新執行緒。翻過原始碼之後才搞清楚,這裡記錄下來。
public interface Runnable {
/**
* Starts executing the active part of the class' code. This method is
* called when a thread is started that has been created with a class which
* implements {@code Runnable}.
*/
public void run();
}
原始碼裡只有一個 run() 方法。如果你直接呼叫 runnable.run(),那段程式碼仍然跑在主執行緒(UI 執行緒)上。
實測驗證:
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
textView.setText("runable"); // 直接改 UI,居然沒報錯?
Log.d("hello", "runable");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runnable.run();
Log.d("hello", "OK");
}
結果:「runable」一定完整輸出十次之後,才轮到「OK」。這證明 run() 就是一次普通的同步方法呼叫,沒有任何並行發生。
看類別宣告:
public class Thread implements Runnable {
最直接的一行:Thread 實作了 Runnable 介面。接著看建構子:
public Thread() {
create(null, null, null, 0);
}
其他建構子最終也都呼叫 create():
private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
Thread currentThread = Thread.currentThread();
if (group == null) {
group = currentThread.getThreadGroup();
}
if (group.isDestroyed()) {
throw new IllegalThreadStateException("Group already destroyed");
}
this.group = group;
synchronized (Thread.class) {
id = ++Thread.count;
}
if (threadName == null) {
this.name = "Thread-" + id;
} else {
this.name = threadName;
}
this.target = runnable; // ★ 關鍵就是這一行
this.stackSize = stackSize;
this.priority = currentThread.getPriority();
this.contextClassLoader = currentThread.contextClassLoader;
if (currentThread.inheritableValues != null) {
inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues);
}
this.group.addThread(this);
}
原始碼很長,但只需要看 this.target = runnable; 這一行——Thread 把你傳進來的 Runnable 存成成員變數 target。
再看 Thread 自己的 run():
public void run() {
if (target != null) {
target.run(); // ★ 由 Thread 幫你呼叫 Runnable 的 run
}
}
以及 start():
/**
* Starts the new Thread of execution. The run() method of the receiver
* will be called by the receiver Thread itself (and not the Thread
* calling start()).
*
* @throws IllegalThreadStateException - if this thread has already started.
*/
public synchronized void start() {
checkNotStarted();
hasBeenStarted = true;
nativeCreate(this, stackSize, daemon); // ★ 這裡才是真的向系統要求一條新執行緒
}
至此,兩個方法的差別就清楚了。
run(),而呼叫 start() 的地方不必等它跑完就能繼續往下走。這才是多執行緒。run() 跑完才會繼續。達不到寫執行緒的目的。結論:只有 start() 會啟動執行緒;run() 只是一次普通的方法呼叫。 把需要並行處理的程式碼放在 run() 裡,由 start() 觸發執行緒去呼叫它,這是 JVM 的機制使然。run() 必須是 public、回傳 void。
Thread t = new Thread(runnable);
t.start();
Log.d("hello", "ok");
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Log.d("hello", "runable");
}
}
};
執行流程:
this.target = runnable;。t.start(),取得 CPU 時間片後執行 run()。run() 內部呼叫 target.run(),也就是在子執行緒中執行 Runnable 的 run()。輸出:
06-13 19:32:26.252 21369-21369/? D/hello: ok 06-13 19:32:26.252 21369-21429/? D/hello: runable 06-13 19:32:26.252 21369-21429/? D/hello: runable ...(共十次)
注意「ok」印在 21369(主執行緒),而「runable」印在 21429(子執行緒),而且順序顛倒了——這就是真開了執行緒的證據。
前面那個 runnable.run() 裡明明寫了 textview.setText() 卻沒報錯,看起來很矛盾。但如果在按鈕的 onClick 裡改用 t.start() 去改 UI,就會立刻爆炸:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
t.start();
}
});
錯誤訊息:
FATAL EXCEPTION: Thread-76777 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
原因在於 ViewRootImpl 的建立時機:
onCreate 執行期間,View 樹尚未完成掛載,ViewRootImpl 還沒建立完成。此時的 UI 操作不會觸發「只有建立 View 的執行緒才能修改它」這項檢查,所以僥倖沒報錯。ViewRootImpl 存在且記錄了建立它的執行緒。這時任何非該執行緒的 UI 操作都會被攔下並拋出例外。規則本身沒有例外:只有建立該 View 的執行緒才能修改和更新它。 而 ViewRootImpl 是在 ActivityThread 的主執行緒中建立的,所以只有主執行緒能更新 UI。前面那個例子只是恰好落在檢查生效之前的空窗期,不是真的允許。
new Thread(runnable).start(),或直接丟進執行緒池。runOnUiThread()、View.post()、Handler,或 Kotlin 的協程 withContext(Dispatchers.Main)。run() 期待並行,那只是同步呼叫。
Android Studio 升級後設定全部重來?兩步驟找回舊配置
把 Android Studio 升級到 1.5 之後,發現所有個人化設定全部回到初始狀態:主題外觀、字型大小與顏色、快捷鍵配置,一夕之間歸零。當下確實有點錯愕。 問題出
Android 自動連線指定 Wi-Fi:免密碼與指定密碼都能搞定
接到一個需求:不掃描、不跳出系統選單,直接連上指定的 Wi-Fi(而且是這台裝置從沒連過的)。於是動手寫了個 Demo 驗證。 一、先看運行結果 畫面上兩個輸入框,上面
ListView 實現加載不同 Item 布局的詳解
在 Android 應用開發中,ListView 幾乎是必備組件,通常用於展示列表類型的數據。普通的數據展示並不難,借助 Volley、Xutils 等框架請求數據,再配
Android 面試重點:Activity 與 Service 的五種交互方式
Activity 與 Service 該怎麼溝通,是面試中幾乎必問的題目。常見答案有五種:廣播、共享檔案、Messenger(信使)、自訂介面、AIDL。本文把這五種做法