In MessageQueue, does Message enqueue use the head-inserting method or the tail-inserting method?

The internal implementation of MessageQueue is actually a singly linked list. From the source code of Message.java, you can see that there is a Message next;member variable in the class, indicating that Message is a node of the singly linked list.

public final class Message implements Parcelable {
    
    
	...
    /*package*/ long when; //单链表排序的依据
    
	... 
    
    /*package*/ Handler target; //保存Message是被哪个Handler发送的,谁发送的谁处理
    
    /*package*/ Runnable callback; // 保存runOnUiThread()方法的入参Runnable
    
    // sometimes we store linked lists of these things
    /*package*/ Message next; //这是单链表节点的标志
	...
}

Since the MessageQueue is implemented by a singly linked list, does the Message in the MessageQueue use the head insertion method or the tail insertion method?
Let me talk about the conclusion first: head insertion and tail insertion are useful, but not all Message enqueues use the head insertion method, and not all Message enqueues use the tail insertion method. It is sorted according to the numerical value of the member variable when, and finds a suitable position to insert.

What is the meaning of the member variable when in Message?

Singly linked lists are whensorted. The value of when is generated in the sendMessageDelayed() method of Handler.java.

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
    
    
        if (delayMillis < 0) {
    
    
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

SystemClock.uptimeMillis()What the hell is that?
SystemClock is provided by Android SDK, the path is /frameworks/base/core/java/android/os/SystemClock.java , this method indicates the total time from booting to the present, in milliseconds. Another method, which is commonly used in JDK, is to get the current time: System.currentTimeMillis(), which is obtained from 00:00:00 GMT on January 1, 1970
(Greenwich Mean Time, Greenwich Mean Time, which stipulates that the sun passes through the suburbs of London, England every day The Royal Greenwich Observatory's time is 12:00 noon)
to the present milliseconds, note that it is not Beijing time. System.currentTimeMillis()I have a dedicated article on this .

when=total time from startup to now+delay time. The unit is milliseconds.

System.currentTimeMillis() and SystemClock.uptimeMillis()
Android message mechanism—MessageQuene insertion and reading algorithm

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/131453161