Android Runnable 運行在那個線程

來源:互聯網
上載者:User

Runnable 並不一定是新開一個線程,比如下面的調用方法就是運行在UI主線程中的:

Handler mHandler=new Handler();mHandler.post(new Runnable(){@Overridepublic 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。

有關 Looper、Handler,Thread 關係可以看這篇部落格:

Android 的訊息佇列模型

http://www.cnblogs.com/ghj1976/archive/2011/05/06/2038469.html

 

這裡我們看代碼 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的匿名內部類

這種情況下,由於不是在新的線程中使用,所以千萬別做複雜的計算邏輯。

參考資料:

Android中的Handler, Looper, MessageQueue和Thread

http://www.cnblogs.com/xirihanlin/archive/2011/04/11/2012746.html

Android系列之Message機制的靈活應用

http://tech.ddvip.com/2010-07/1280393505158258_3.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.