2011-12-01 56 views
2

我的Android應用程序中的非UI線程包含Handler對象,並使用post()方法將Runnable的實現添加到此Handler。Handler是否同時執行Runnable

從閱讀API看來,Handler似乎使用了一個隊列。這是否意味着如果我將()2個Runnables發佈到隊列中,那麼第二個只能在完成第一個Runnable的運行方法時纔開始執行?

只是想確認一下,因爲我在我的應用程序中看到了一些多線程問題。

感謝

回答

2

(按我理解你的問題)

按照該API,處理器使用的MessageQueue,第二運行執行第一完成後開始,

一個處理程序允許您發送和處理與線程的MessageQueue關聯的Message和Runnable對象。每個Handler實例都與單個線程和該線程的消息隊列相關聯。當您創建一個新的處理程序時,它將綁定到正在創建它的線程的線程/消息隊列 - 此後,它將消息和可運行消息傳遞到該消息隊列,並在消息出來時執行它們隊列。

處理程序有兩個主要用途:(1)安排將來要執行的消息和可運行子程序;和(2)排隊在不同於你自己的線程上執行的動作。

1
A Handler allows you to send and process Message and Runnable 
objects associated with a thread's MessageQueue. Each Handler 
instance is associated with a single thread and that thread's 
message queue. When you create a new Handler, it is bound to 
the thread/message queue of the thread that is creating it 
-- from that point on, it will deliver messages and runnables 
to that message queue and execute them as they come out of the 
message queue. 

There are two main uses for a Handler: 
-1- to schedule messages and runnables to be 
executed as some point in the future; and 
-2- to enqueue an action to be performed on a 
different thread than your own. 

引用自:http://developer.android.com/reference/android/os/Handler.html 涉及到你的問題,它是YES,後一日的Runnable做第二人會跑。