Android中多线程同步

本文详细介绍了Android中实现多线程同步的多种方法,包括Handler机制、runOnUiThread、View.post、AsyncTask、Synchronized锁、ReentrantLock、volatile关键字、wait-notify机制以及ThreadLocal的使用。每种方法都有其适用场景,提供了理解和应用多线程同步的全面指南。
摘要由CSDN通过智能技术生成

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值