其他
万字图文,带你学懂Handler和内存屏障
https://juejin.cn/user/2840793776393847/posts
Looper.prepare()、Handler()、Looper.loop() 总流程 收发消息 分发消息
...
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
...
收发消息一体 handleCallback(msg) 收发消息分开 mCallback.handleMessage(msg) handleMessage(msg)
收发一体
handleCallback(msg)
private TextView msgTv;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//消息收发一体
new Thread(new Runnable() {
@Override public void run() {
String info = "第一种方式";
mHandler.post(new Runnable() {
@Override public void run() {
msgTv.setText(info);
}
});
}
}).start();
}
}
收发分开
mCallback.handleMessage(msg)
private TextView msgTv;
private Handler mHandler = new Handler(new Handler.Callback() {
//接收消息,刷新UI
@Override public boolean handleMessage(@NonNull Message msg) {
if (msg.what == 1) {
msgTv.setText(msg.obj.toString());
}
//false 重写Handler类的handleMessage会被调用, true 不会被调用
return false;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//发送消息
new Thread(new Runnable() {
@Override public void run() {
Message message = Message.obtain();
message.what = 1;
message.obj = "第二种方式 --- 1";
mHandler.sendMessage(message);
}
}).start();
}
}
handleMessage(msg)
private TextView msgTv;
private Handler mHandler = new Handler() {
//接收消息,刷新UI
@Override public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
msgTv.setText(msg.obj.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//发送消息
new Thread(new Runnable() {
@Override public void run() {
Message message = Message.obtain();
message.what = 1;
message.obj = "第二种方式 --- 2";
mHandler.sendMessage(message);
}
}).start();
}
}
prepare和loop
@Override public void run() {
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
});
...
public static void main(String[] args) {
...
//主线程Looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
//主线程的loop开始循环
Looper.loop();
...
}
...
Looper.prepare():生成Looper对象,set在ThreadLocal里 handler构造函数:通过Looper.myLooper()获取到ThreadLocal的Looper对象 Looper.loop():内部有个死循环,开始事件分发了;这也是最复杂,干活最多的方法
Looper.prepare()
...
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));
}
...
Handler()
...
@Deprecated
public Handler() {
this(null, false);
}
public Handler(@Nullable Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
...
...
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
...
Message msg = queue.next():遍历消息 msg.target.dispatchMessage(msg):分发消息 msg.recycleUnchecked():消息回收,进入消息池
...
public static void loop() {
final Looper me = myLooper();
...
final MessageQueue queue = me.mQueue;
...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
try {
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
....
msg.recycleUnchecked();
}
}
...
发送消息
post(Runnable):发送和接受消息都在post中完成 sendMessage(msg):需要自己传入Message消息对象
此方法给msg的target赋值当前handler之后,才进行将消息添加的消息队列的操作 msg.setAsynchronous(true):设置Message属性为异步,默认都为同步;设置为异步的条件,需要手动在Handler构造方法里面设置
...
//post
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
//生成Message对象
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
//sendMessage方法
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
///将Message加入详细队列
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
//设置target
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
//设置为异步方法
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
...
...
boolean enqueueMessage(Message msg, long when) {
...
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;
}
...
接收消息
...
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
...
触发条件:Message消息中实现了handleCallback回调 现在基本上只能使用post()方法了,setCallback(Runnable r) 被表明为@UnsupportedAppUsage,被hide了,没法调用,如果使用反射倒是可以调用,但是没必要。。。
触发条件
使用sendMessage方法发送消息 实现Handler的Callback回调 mCallback.handleMessage(msg)返回为false
分发的消息,会在Handler中实现的回调中分发
触发条件
使用sendMessage方法发送消息 未实现Handler的Callback回调或者mCallback.handleMessage(msg)返回为true
需要重写Handler类的handlerMessage方法
Looper.loop():精简了巨量源码 Message msg = queue.next():遍历消息 msg.target.dispatchMessage(msg):分发消息 msg.recycleUnchecked():消息回收,进入消息池
...
public static void loop() {
final Looper me = myLooper();
...
final MessageQueue queue = me.mQueue;
...
for (;;) {
//遍历消息池,获取下一可用消息
Message msg = queue.next(); // might block
...
try {
//分发消息
msg.target.dispatchMessage(msg);
...
} catch (Exception exception) {
...
} finally {
...
}
....
//回收消息,进图消息池
msg.recycleUnchecked();
}
}
...
遍历消息
...
Message next() {
final long ptr = mPtr;
...
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
...
//阻塞,除非到了超时时间或者唤醒
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
// 这是关于同步屏障(SyncBarrier)的知识,放在同步屏障栏目讲
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//每个消息处理有耗时时间,之间存在一个时间间隔(when是将要执行的时间点)。
//如果当前时刻还没到执行时刻(when),计算时间差值,传入nativePollOnce定义唤醒阻塞的时间
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
mBlocked = false;
//该操作是把异步消息单独从消息队列里面提出来,然后返回,返回之后,该异步消息就从消息队列里面剔除了
//mMessage仍处于未分发的同步消息位置
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
//返回符合条件的Message
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
//这是处理调用IdleHandler的操作,有几个条件
//1、当前消息队列为空(mMessages == null)
//2、已经到了可以分发下一消息的时刻(now < mMessages.when)
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
nextPollTimeoutMillis大于等于零,会规定在此段时间内休眠,然后唤醒 消息队列为空时,nextPollTimeoutMillis为-1,进入阻塞;重新有消息进入队列,插入头结点的时候会触发nativeWake唤醒方法
会将msg消息死循环到末尾节点,除非碰到异步方法 如果碰到同步屏障消息,理论上会一直死循环上面操作,并不会返回消息,除非,同步屏障消息被移除消息队列
当前时刻小于返回消息超时时间:进入阻塞,计算时间差,给nativePollOnce设置超时时间,超时时间一到,解除阻塞,重新循环取消息 当前时刻大于返回消息超时时间:获取可用消息返回 when这个变量可能比较疑惑,这玩意是怎么来的,初始值不都是0吗?
实际上我们发送消息的时候,可以发送延时消息:sendMessageDelayed(@NonNull Message msg, long delayMillis) MessageQueue类中的enqueueMessage方法,会把延时时间( SystemClock.uptimeMillis() + delayMillis)赋值给Message对象的when字段
分发消息
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
消息池
首先会将当前已经分发处理的消息,相关属性全部重置,flags也标志可用 消息池的头结点会赋值为当前回收消息的下一节点,当前消息成为消息池头结点 简言之:回收消息插入消息池,当做头结点 需要注意的是:消息池有最大的容量,如果消息池大于等于默认设置的最大容量,将不再接受回收消息入池
默认最大容量为50:MAX_POOL_SIZE = 50
...
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
如果消息池不为空:直接取消息池的头结点,被取走头结点的下一节点成为消息池的头结点 如果消息池为空:直接返回新的Message实例
...
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
/ IdleHandler /
...
Message next() {
final long ptr = mPtr;
...
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
...
//阻塞,除非到了超时时间或者唤醒
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
...
//这是处理调用IdleHandler的操作,有几个条件
//1、当前消息队列为空(mMessages == null)
//2、未到到了可以分发下一消息的时刻(now < mMessages.when)
//3、pendingIdleHandlerCount < 0表明:只会在此for循环里执行一次处理IdleHandler操作
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
当前消息队列为空(mMessages == null) 或 未到分发返回消息的时刻 在每次获取可用消息的死循环中,IdleHandler只会被处理一次:处理一次后pendingIdleHandlerCount为0,其循环不可再被执行
返回false,执行后,IdleHandler将会从IdleHandler列表中移除,只能执行一次:默认false 返回true,每次分发返回消息的时候,都有机会被执行:处于保活状态
...
/**
* Callback interface for discovering when a thread is going to block
* waiting for more messages.
*/
public static interface IdleHandler {
/**
* Called when the message queue has run out of messages and will now
* wait for more. Return true to keep your idle handler active, false
* to have it removed. This may be called if there are still messages
* pending in the queue, but they are all scheduled to be dispatched
* after the current time.
*/
boolean queueIdle();
}
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
public void removeIdleHandler(@NonNull IdleHandler handler) {
synchronized (this) {
mIdleHandlers.remove(handler);
}
}
public class MainActivity extends AppCompatActivity {
private TextView msgTv;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//添加IdleHandler实现类
mHandler.getLooper().getQueue().addIdleHandler(new InfoIdleHandler("我是IdleHandler"));
mHandler.getLooper().getQueue().addIdleHandler(new InfoIdleHandler("我是大帅比"));
//消息收发一体
new Thread(new Runnable() {
@Override public void run() {
String info = "第一种方式";
mHandler.post(new Runnable() {
@Override public void run() {
msgTv.setText(info);
}
});
}
}).start();
}
//实现IdleHandler类
class InfoIdleHandler implements MessageQueue.IdleHandler {
private String msg;
InfoIdleHandler(String msg) {
this.msg = msg;
}
@Override
public boolean queueIdle() {
msgTv.setText(msg);
return false;
}
}
}
总结
/ 同步屏障 /
前置知识
同步和异步消息
FLAG_ASYNCHRONOUS = 1 << 1:所以FLAG_ASYNCHRONOUS为2 同步消息:flags为0或者1的时候,isAsynchronous返回false,此时该消息标定为同步消息
flags为0,1:同步消息
异步消息:理论上只要按照位操作,左往右,第二位为1的数,isAsynchronous返回true;但是,Message里面基本只使用了:0,1,2,可得出结论
flags为2:异步消息
return (flags & FLAG_ASYNCHRONOUS) != 0;
}
public void setAsynchronous(boolean async) {
if (async) {
flags |= FLAG_ASYNCHRONOUS;
} else {
flags &= ~FLAG_ASYNCHRONOUS;
}
}
//设置异步消息标记
msg.setAsynchronous(true);
默认消息类型
这地方给Message类的target赋值了! 说明:只要使用post或sendMessage之类发送消息,其消息就绝不可能是同步屏障消息!
只要mAsynchronous为true的话,我们的消息都会异步消息 只要mAsynchronous为false的话,我们的消息都会同步消息
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
this(null, false);
}
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback) {
this(looper, callback, false);
}
这下清楚了!如果不做特殊设置的话:默认消息都是同步消息 默认消息都会给其target熟悉赋值:默认消息都不是同步屏障消息
生成同步屏障消息
sync:同步 barrier:屏障,障碍物 ---> 同步屏障 同步屏障实际挺能代表其含义的,它能屏蔽消息队列中后续所有的同步方法分发
...
@UnsupportedAppUsage
@TestApi
public int postSyncBarrier() {
return postSyncBarrier(SystemClock.uptimeMillis());
}
private int postSyncBarrier(long when) {
// Enqueue a new sync barrier token.
// We don't need to wake the queue because the purpose of a barrier is to stall it.
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.markInUse();
msg.when = when;
msg.arg1 = token;
Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
}
if (prev != null) { // invariant: p == prev.next
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}
从消息池取一个可用消息 头结点(mMessage)是否为空
不为空:插到头结点的下一节点位置 为空:成为头结点
同步屏障消息是直接插到消息队列,他没有设置target属性且不经过enqueueMessage方法,故其target属性为null
同步屏障流程
...
Message next() {
final long ptr = mPtr;
...
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
...
//阻塞,除非到了超时时间或者唤醒
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
// 这是关于同步屏障(SyncBarrier)的逻辑块
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//每个消息处理有耗时时间,之间存在一个时间间隔(when是将要执行的时间点)。
//如果当前时刻还没到执行时刻(when),计算时间差值,传入nativePollOnce定义唤醒阻塞的时间
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
mBlocked = false;
//该操作是把异步消息单独从消息队列里面提出来,然后返回,返回之后,该异步消息就从消息队列里面剔除了
//mMessage仍处于未分发的同步消息位置
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
//返回符合条件的Message
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
...
}
...
}
}
msg移到尾结点,也就是移到了消息队列尾结点,将自身赋值为null(尾结点的next) 遇上标记为异步的消息,放行该消息进行后续分发
当我们在同步屏障逻辑里面,将msg自身移到尾结点,并赋值为null(尾结点的next) msg为null,是无法进行后续分发操作,会重新进行循环流程 mMessage头结点重新将自身位置赋值给msg,继续上述的重复过程 可以发现,上述逻辑确实起到了同步屏障的作用,屏蔽了其所有后续同步消息的分发;只有移除消息队列中的该条同步屏障消息,才能继续进行同步消息的分发
消息队列中如果有异步消息,同步屏障的逻辑会放行异步消息 同步屏障里面堆prevMsg赋值了!请记住在整个方法里面,只有同步屏障逻辑里面堆prevMsg赋值了!这个参数为null与否,对消息队列节点影响很大 prevMsg为空:会直接将msg的next赋值给mMessage;说明分发完消息后,会直接移除头结点,将头结点的下一节点赋值为头结点 prevMsg不为空:不会对mMessage投节点操作;会将分发消息的上一节点的下一节点位置,换成分发节点的下一节点,有点绕 通过上面分析,可知;异步消息分发完后,会将其直接从消息队列中移除,头结点位置不变
同步屏障作用
Device类
这说明,我们无法调用这个方法;事实上,我们连Device类都无法调用,Device属于被隐藏的类,和他同一目录的还有Event和Hid,这些类系统都不想对外暴露 这就很鸡贼了,说明插入同步屏障的消息的方法,系统确实不想对外暴露;当然不包括非常规方法:反射
...
private class DeviceHandler extends Handler {
...
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_OPEN_DEVICE:
...
pauseEvents();
break;
...
}
}
public void pauseEvents() {
mBarrierToken = getLooper().myQueue().postSyncBarrier();
}
public void resumeEvents() {
getLooper().myQueue().removeSyncBarrier(mBarrierToken);
mBarrierToken = 0;
}
}
...
private class DeviceHandler extends Handler {
...
public void pauseEvents() {
mBarrierToken = getLooper().myQueue().postSyncBarrier();
}
public void resumeEvents() {
getLooper().myQueue().removeSyncBarrier(mBarrierToken);
mBarrierToken = 0;
}
}
private class DeviceCallback {
public void onDeviceOpen() {
mHandler.resumeEvents();
}
....
}
打开设备时,在消息队列头结点下一节点位置插入同步屏障消息,屏蔽后续所有同步消息 完成开机后,移除同步屏障消息 总结:很明显,这是尽量的提升打开设备速度,不被其它次等重要的事件干扰
ViewRootImpl类
...
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
我们调用View的requestLayout或者invalidate时,最终都会触发ViewRootImp执行scheduleTraversals()方法。这个方法中ViewRootImp会通过Choreographer来注册个接收Vsync的监听,当接收到系统体层发送来的Vsync后我们就执行doTraversal()来重新绘制界面。通过上面的分析我们调用invalidate等刷新操作时,系统并不会立即刷新界面,而是等到Vsync消息后才会刷新页面。
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
void scheduleTraversals() {
if (!mTraversalScheduled) {
...
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
...
}
}
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
总结
总结
消息插入区别
取消息:关于取消息,都是取的mMessage,可以理解为,取消息队列的头结点 正常发送消息:插入到消息队列的尾结点 消息屏障消息:插入到消息队列头结点的下一节点
Vsync
Vsync 信号一般是由硬件产生的,现在手机一般为60hz~120hz,每秒刷新60到120次,一个时间片算一帧 每个 Vsync 信号之间的时间就是一帧的时间段
总结
同步屏障能确保消息队列中的异步消息,会被优先执行 鉴于正常消息和同步屏障消息插入消息队列的区别:同步屏障能够及时的屏障队列中的同步消息 某些极端场景:发送的消息,在分发的时候,可能会存一帧延时 极端场景:Vsync信号到来之后,立马执行了RequestLayout等操作 同步屏障能确保在UI刷新中:Vsync信号到来后,能够立马执行真正的绘制页面操作
正常情况,请继续使用同步消息 特殊情况,需要自己发送的消息被优先处理:可以使用异步消息
/ 考点 /
当消息队列中消息为空时,触发MessageQueue中的nativePollOnce方法,线程休眠,释放CPU资源 消息插入消息队列,会触发nativeWake唤醒方法,解除主线程的休眠状态
当插入消息到消息队列中,为消息队列头结点的时候,会触发唤醒方法 当插入消息到消息队列中,在头结点之后,链中位置的时候,不会触发唤醒方法
综上:消息队列为空,会阻塞主线程,释放资源;消息队列为空,插入消息时候,会触发唤醒机制
这套逻辑能保证主线程最大程度利用CPU资源,且能及时休眠自身,不会造成资源浪费
本质上,主线程的运行,整体上都是以事件(Message)为驱动的
3、为什么不建议在子线程中更新UI?