Android-多线程和进程
http://www.cnblogs.com/plokmju/p/android_ProcessOrThread.html
对于单线程模型,Android有两个规则:
- 不能阻塞UI线程
- 不能在工作线程中访问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。