Android中多线程同步的方法很多:
1、最常用的 Handler机制,我们在工作线程中完成耗时的操作,然后把结果通过Handler + message 的方式抛给UI线程进行处理,还可以他通过Handler的post(), postDelay(),传递一个Runnable到UI线程中进行处理
2、activity的runOnUiThread(Runnable action)把action传递给UI线程处理我们查看源码
/** * 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(); } }
发现runOnUiThread其实就是调的UI线程的Handler的post方法实现的
3、View 的post(), postDelay()
/**
* <p>Causes the Runnable to be added to the message queue.
* The runnable will be run on the user interface thread.</p>
*
* @param action The Runnable that will be executed.
*
* @return 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.
*
* @see #postDelayed
* @see #removeCallbacks
*/
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return a