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

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




更多相关文章

  1. Android(安卓)Exception No such table android_metadata
  2. android中Http访问时 connection.getResponseCode()不被执行,且报
  3. Android(安卓)获取应用运行时长
  4. android handler的警告Handler Class Should be Static or Leaks
  5. Android(安卓)Fragment生命周期深入探究
  6. Android(安卓)-- SurfaceFlinger 合成主线程 系列 (三)
  7. 2011.09.14(2)——— android tabhost位于底部
  8. Android(安卓)Scroll
  9. Android(安卓)菜单(OptionMenu)大全

随机推荐

  1. Android手机开发:获取GPS信息
  2. Android中Broadcast的Intent大全
  3. 为ListActivity 添加Button
  4. android 使用代码实现 RelativeLayout布
  5. Link Android(安卓)Source Code to Eclip
  6. 【NFC】Android(安卓)NFC API Reference
  7. Android(安卓)ViewPager 中嵌套webview
  8. Android如何从服务器获取图片
  9. Android:Gallery
  10. Android采用SAX解析XML文档