Android Runnable 執行在那個執行緒
Handler mHandler=new Handler(); mHandler.post(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub } });
官方對這個方法的解釋如下,注意其中的:“The runnable will be run on the user interface thread. ”
boolean android.view.View .post(Runnable action)
Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.
Parameters:
action The Runnable that will be executed.
Returns:
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.
我們可以通過呼叫handler的post方法,把Runnable物件(一般是Runnable的子類)傳過去;handler會在looper中呼叫這個Runnable的Run方法執行。
Runnable是一個介面,不是一個執行緒,一般執行緒會實現Runnable。
這裡我們看程式碼 mHandler.post(new Runnable(){ 好像是new 了一個 interface, 其實是new的一個實現Runnable的匿名內部類(Inner Anonymous Class),這是很簡練的寫法。
上面的程式碼可以看成是: new anonymousClass() implement interface{ [改寫interface method]}
Runnable是一個介面,不是一個執行緒,一般執行緒會實現Runnable。 所以如果我們使用匿名內部類是執行在UI主執行緒的,如果我們使用實現這個Runnable介面的執行緒類,則是執行在對應執行緒的。
具體來說,這個函式的工作原理如下:
View.post(Runnable)方法。在post(Runnable action)方法裡,View獲得當前執行緒(即UI執行緒)的Handler,然後將action物件post到Handler裡。在Handler裡,它將傳遞過來的action物件包裝成一個Message(Message的callback為action),然後將其投入UI執行緒的訊息迴圈中。在Handler再次處理該Message時,有一條分支(未解釋的那條)就是為它所設,直接呼叫runnable的run方法。而此時,已經路由到UI執行緒裡,因此,我們可以毫無顧慮的來更新UI。
如下圖,前面看到的程式碼,我們這裡Message的callback為一個Runnable的匿名內部類
這種情況下,由於不是在新的執行緒中使用,所以千萬別做複雜的計算邏輯。
參考資料: