http://www.cnblogs.com/plokmju/p/android_ProcessOrThread.html

对于单线程模型,Android有两个规则:

  1. 不能阻塞UI线程
  2. 不能在工作线程中访问Android UI ToolKit包下的组件。

Android提供几种方法可以从其他线程中访问UI线程:

  • Activity.runOnUiThread(Runnable):运行在指定的UI线程上,如果当前线程是UI线程,那么立即执行,如果当前线程不是UI线程,则发布到UI线程的事件队列中。
  • View.post(Runnable):将事件发布到UI线程中,立即被执行。
  • View.postDelayed(Runnanle,long):将事件发布到UI线程中,延迟被执行,延迟数为传递的long参数。

其中runOnUiThread源码如下:

http://www.2cto.com/kf/201410/342883.html

 * Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
*
* @param action the action to run on the UI thread
* public final void runOnUiThread(Runnable action) {
* if (Thread.currentThread() != mUiThread) {
* mHandler.post(action);
* } else {
* action.run();
* }
* }

其实也就是调用了handler里的post,http://www.cnblogs.com/qlky/p/5657924.html

这篇文章解释得更为详细:http://blog.csdn.net/u012995136/article/details/49701095

对于第二个View.post,原理如下:

我们可以通过调用handler的post方法,把Runnable对象(一般是Runnable的子类)传过去;handler会在looper中调用这个Runnable的Run方法执行。

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。

最新文章

  1. TCP滑动窗口机制
  2. regeneratorRuntime未定义
  3. 20个人艰不拆的事实:知道真相的我眼泪掉下来 T.T
  4. 动态规划(一)——最长公共子序列和最长公共子串
  5. webpack笔记_(3)_First_Project
  6. Codeforces Round #147 (Div. 2)
  7. sql server 修改列类型
  8. easyui源码翻译1.32--PropertyGrid(属性表格)
  9. 【结构型】Facade模式
  10. 工资不高也要给自己放假 这几款APP估计你用得上
  11. 入职这一段时间的总结,Don't Repeat Yourself.
  12. Mybaits简诉
  13. [机器学习]模型评价参数,准确率,召回率,F1-score
  14. requests之一:HTTP OAUTH认证(1)图形解释流程
  15. Servlet基本知识总结
  16. GNOME下让QT应用使用adwaita主题统一外观
  17. Excel自动建组
  18. Kettle实现数据抽取、转换、装入和加载数据-数据转移ETL工具
  19. minIni: A minimal INI file parser
  20. 未预期的符号 `$'{\r'' 附近有语法错误

热门文章

  1. MySQL5.7 mysql.user创建用户
  2. IOS面试题(一)
  3. 【C/C++】10分钟教你用C++写一个贪吃蛇附带AI功能(附源代码详解和下载)
  4. POJ3076 Sudoku
  5. Selenium三种等待元素的方式及代码,需要特别注意implicitlyWait的用法
  6. python全栈开发_day12_装饰器
  7. python量化分析系列之---5行代码实现1秒内获取一次所有股票的实时分笔数据
  8. request.upload.addEventListener in not a function。
  9. 利用JS获取本地时间和服务器时间
  10. mouseover和mouseenter闪烁的问题