当前位置:网站首页>Exploration of SendMessage principle of advanced handler
Exploration of SendMessage principle of advanced handler
2022-04-23 07:15:00 【Lance_ w】
Handler Advanced sendMessage
This paper mainly further explores Handler, Main introduction Handler How to send messages ?
Used to Handler You must be familiar with the following methods :
sendMessage(Message msg);// Send a message now
sendMessageAtTime(Message msg, long atTime);// Send a message at a certain point in time
sendMessageDelayed(Message msg, long delayedTime);// Delay sending a message for a period of time at the current point in time
These are three Handler How to send a message , The difference is that the time points sent are inconsistent , But in fact, all three methods are implemented in the end Handler The same method within , There is only a slight difference in parameters :
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
sendMessage(Message msg);
// Corresponding
sendMessageDelayed(msg, 0);
sendMessageAtTime(Message msg, long atTime);
// Corresponding
sendMessageDelayed(msg, atTime)
sendMessageDelayed(Message msg, long delayedTime);
// Corresponding
sendMessageDelayed(msg, SystemClock.uptimeMillis() + delayedTime)
As you can see from the code above , The final message is sent after it is passed in Message Object and corresponding need to be sent Message The timing of the .
We conjecture that ,Handler Is sending a message based on Message Set a timer at the time point of sending to let Message Sent out at a certain point in time ?
If that's all , You underestimate google My big cows . Have you been a little impatient to think about how the Bulls did it ?
Here we will skip some simple procedures called in the middle , be familiar with Java You can understand at a glance , Go straight to the core of sending messages ,
We all know Handler Sending a message is actually going to Message First put it into MessageQueue, If I can see this article, I default that everyone is already familiar with
Handler It's the basic principle of , If you are not familiar with , You can refer to
Handler A comprehensive interpretation of the principle of message mechanism
Look directly here Message Put in MessageQueue The process of :
boolean enqueueMessage(Message msg, long when) {
...// More code , Omit some code that throws exceptions
synchronized (this) {
...
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
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;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
Focus on the if-else here , Take them apart one by one :
if (p == null || when == 0 || when < p.when) {//p It is the present. MessageQueue Team leader Message
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
}
If the current queue has nothing else to send Message; Add current or new Message The time point is 0( Messages that need to be sent immediately );
Add current or new Message The time point to be sent is smaller than the current one MessageQueue Queue header Message The timing of the ( That is, the currently added Message Need to be in the present MessageQueue Queue header Message Was sent before ) when , It will enter into if In the code block . What to do at this time is to add the current new Message Insert into MessageQueue The team leader of ( Do not understand how to insert, you can refer to Handler A comprehensive interpretation of the principle of message mechanism ,
Message The storage of is in the form of linked list ,next Equivalent to the tail pointer of the linked list ).
There is also an assignment operation (needWake = mBlocked), Here's the explanation , You can see that there are comments in the code , New head , Then if it's blocked , Need to wake up the thread . Why is there thread blocking ? Actually MessageQueue Internal messages are arranged from small to large according to the time point of sending , We will analyze later , From the current if Inside when Judgment can also tell one or two , Head of the team Message When the time point of transmission is not reached , It indicates that all the current messages have not reached the sending time , It said ,Handler Sending a message is not sent through a timer , therefore , Be the head of the team Message( Need to send recently Message) When the sending time point is not reached , Thread blocked , Therefore, we need to see whether we need to wake up the thread according to whether the thread is blocked , So that the new Message Can be sent out in time , Not blocked . The thread wakes up through native To achieve .
Let's take a look at else Code inside :
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
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;
Perform the else Statement inside , Describes the currently added Message It's in the present MessqgeQueue Team leader Message It will be sent later , The above analysis if Part of the code said Message It is arranged according to the time of sending as needed MessageQueue Medium , there for The actual operation of the loop is to find MessageQueue Than the currently added Message The time point that needs to be sent is a large location , take Message Insert in front of it ( In fact, it is an insertion operation of linked list ).
The analysis of this chapter will come to an end here , Then we will analyze it in detail Message from MessageQueue The removal process , You can refer to Handler A comprehensive interpretation of the principle of message mechanism .
The reason for writing this article is to answer two questions .
- sendMessageDelayed How to delay sending messages ?
- sendMessageDelayed It is the result of delaying sending messages through blocking , Will it block the newly added Message?
summary :
- Handler When sending a message ,MessageQueue The messages in are arranged from small to large according to the sending time point ,
If the nearest Message If the sending time is not reached, it will block . - The newly added data will determine the position to be inserted according to the size of the time point , At the same time, you also need to determine whether you need to wake up the thread to send the message of the current queue leader .
版权声明
本文为[Lance_ w]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230608223865.html
边栏推荐
猜你喜欢

C# EF mysql更新datetime字段报错Modifying a column with the ‘Identity‘ pattern is not supported

机器学习 三: 基于逻辑回归的分类预测

Oracle Job定时任务的使用详解

ffmpeg常用命令

组件化学习(2)Arouter原理学习

What did you do during the internship

useReducer基本用法
![[2021 book recommendation] effortless app development with Oracle visual builder](/img/db/d8802b42d5374e4117db638a0b82b0.png)
[2021 book recommendation] effortless app development with Oracle visual builder

BottomSheetDialogFragment 与 ListView RecyclerView ScrollView 滑动冲突问题

Android面试计网面经大全【持续更新中。。。】
随机推荐
窗口分析函数LAST_VALUE,FIRST_VALUE,lag,lead
Three methods to realize the rotation of ImageView with its own center as the origin
[exynos4412] [itop4412] [android-k] add product options
AVD Pixel_2_API_24 is already running.If that is not the case, delete the files at C:\Users\admi
MySQL notes 2_ data sheet
DCMTK(DCM4CHE)与DICOOGLE协同工作
MySQL笔记1_数据库
Miscellaneous learning
sys.dbms_scheduler.create_job创建定时任务(功能更强大丰富)
組件化學習
iTOP4412内核反复重启
组件化学习
[recommendation for new books in 2021] professional azure SQL managed database administration
MySQL笔记3_约束_主键约束
Android面试计网面经大全【持续更新中。。。】
Cancel remote dependency and use local dependency
cmder中文乱码问题
js时间获取本周一、周日,判断时间是今天,今天前、后
Using stack to realize queue out and in
机器学习笔记 一:学习思路