Handler

一、Handler核心

线程间如何通讯
Handler通信实现的方案实际上是内存共享的方案

在这里插入图片描述

源于生活高于生活
handler: 地下 - 地上《 消息管理机制:消息-》事物

java main()jvm(一个应用挂掉不影响其他的应用)
功能机:FATAL error
所有的代码,都是handler
lancher (app):zygote -》 jvm -》 ActvityThread.main

ActivityThread的main函数调用了Loop.looper()

	public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

msg为null时退出死循环
应用退出调用quit()函数退出

handler------->
sendMessage ---------->
MessasgeQueue.enqueueMessage //把消息放入消息队列
Looper.loop()-----------------> //死循环调用next()
MessasgeQueue.next() ------------------->//取消息,返回的是Message
handler.dispatchMessage()---------->
handler.handleMessage()

在这里插入图片描述

二、MessageQueue.enqueueMessage()

数据结构: 有单链表实现的优先级队列
Message里面有一个next指向下一个Message的指针
先后顺序,时间
插入排序算法

MessageQueue.enqueueMessage()里面的入队代码:
when时间越小越早执行

                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;

M4比M1晚
M4比M2晚
M4比M3早
在这里插入图片描述

三、MessageQueue.next()

消息队列最前面的Message就是最早要执行的消息,直接取队头就行了

                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

四、Looper

构造函数

私有的,由prepare完成

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

为什么这样初始化?
如果公有的话是不是随便new

如果prepare成功过就会直接获取,不允许继续prepare

一个线程只有一个Looper且不能改----ThreadLocal
MessageQueue 在Looper函数中被new
MessageQueue 是一个容器,不属于某个线程
主线程中只有一个MessageQueue
有多少个MessageQueue 不好说

五、消息机制之同步屏障

msg.target == null
架构思维

MessageQueue.next()中

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                }

如果有一个消息target为null,会循环消息队列中所有消息直到找到msg为同步消息为止(同步消息就是要立即执行的消息)
在这里插入图片描述
什么时候红色的target消失

同步屏障的运用场景:屏幕点击的时候刷新UI
16ms左右 刷新UI: 60HZ的屏幕 (1000/60) 不然闪屏掉帧

同步: 立刻执行 messageQueue.postSyncBarrier() -》立刻执行,不能等别的消息
异步消息:普通消息

next: 取队列的第一个消息先执行
但是里面有个if语句能判断是否有同步消息-----同步屏障

                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }

创建子线程的handler
没办法在主线程创建子线程的handler,因为拿不到子线程的Looper

Thread thread = new Thread() {
	run(){
		Looper.prepare();
		looper = Looper.myLooper();
		threadHandler = new Handler(looper);
		Looper.loop();
	}
	public Looper getLooper(){return looper;}
};
thread.start();

六、HandlerThread

HandlerThread存在的意义:HandlerThread是Thread的子类,就是一个线程,只是它在自己的线程里面帮我们创建了Looper
1.方便实用(a.方便初始化,b.方便获取线程looper)
2.保证了线程安全

public class HandlerThread extends Thread
    public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

七、IntendService

IntendService 会维持一个线程独有的队列,每一个任务都在同一个线程中处理,用的HandlerThread

Service一般用于处理后台耗时任务
应用需要:一项任务分成几个子任务,子任务按顺序先后执行,子任务全部执行完后,这项任务才算成功
这个需求可以用多个线程来处理,一个线程处理完–>下一个线程—>下一个线程
IntendService就可以帮我们完成这个工作。而且,能够很好的管理线程,保证只有一个子线程处理工作,而且是一个一个的完成任务,有条不紊的进行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值