android 进程/线程管理(四)----消息机制的思考(自定义消息机制)

时间:2023-02-05 07:43:00

关于android消息机制 已经写了3篇文章了,想要结束这个系列,总觉得少了点什么?

于是我就在想,android为什么要这个设计消息机制,使用消息机制是现在操作系统基本都会有的特点。

可是android是把消息自己提供给开发者使用!我们可以很简单的就在一个线程中创建一个消息系统,不需要考虑同步,消息队列的存放,绑定。

自己搞一个消息系统麻烦吗?android到底为什么要这么设计呢?

那我们自己先搞一个消息机制看看,到底是个什么情况?

首先消息肯定需要消息队列:

package com.joyfulmath.androidstudy.thread.messagemachine;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import com.joyfulmath.androidstudy.TraceLog; import android.util.AndroidRuntimeException; /*message queue
*
* */
public class MessageQueue {
BlockingQueue<Message> mQueue = null;
private boolean mQuit = false;
public MessageQueue()
{
mQueue = new LinkedBlockingQueue<Message>();
mQueue.clear();
} public boolean enqueueMessage(Message msg, long when)
{
TraceLog.i();
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
} try {
mQueue.put(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TraceLog.i("done");
return true;
} public Message next()
{
TraceLog.i();
Message msg = null;
if(mQuit)
{
return null;
} //wait mQueue msg util we can get one.
try {
msg = mQueue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TraceLog.i(msg.toString());
return msg;
} public synchronized void quit()
{
mQuit = true;
}
}

这里有个问题,就是消息添加和获取的同步问题,尤其是一开始,消息队列没有消息的时候,获取消息会怎样?

我们稍后来看这个问题,先看消息队列的几个函数:

BlockingQueue<Message> mQueue = null;

这个就是实际队列存放的地方,就是一个普通的queue。

然后就是加入消息和取出消息。

其实这2个操作,一般都不在一个线程内,需要考虑同步问题。

最后是退出函数,注意,quit()是消息机制结束的标志,一但设置,整个线程将结束。

我们在来讲讲:

mQueue.put(msg);
msg = mQueue.take();

put就是把消息放入队列,而take则与一般的queue peek方法不同,如果消息队列为空,这个地方会block住,直到有消息

加入队列为止。其实这里有个问题,如何一直没有消息进入队列的话,线程会一直block住。

下面我们看看消息队列的生存位置---线程。

package com.joyfulmath.androidstudy.thread.messagemachine;

import com.joyfulmath.androidstudy.TraceLog;

public class MessageHandlerThread extends Thread {
private Object objsync = new Object(); private boolean mQuite = false;
private Message msg = null;
ThreadLocal<MessageQueue> mThreadLocakMsgQueue = new ThreadLocal<MessageQueue>();
@Override
public void run() {
TraceLog.d("MessageHandlerThread start running");
prepare();
final MessageQueue mQueue = getMessageQueue();
while(true)
{
synchronized (objsync) {
if(mQuite)
{
TraceLog.i("quite msg queue");
break;
}
}
Message msg = mQueue.next();
TraceLog.i("get next msg:"+msg);
if(msg == null)
{
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchHandlerMessage(msg);
} TraceLog.i("thread is done");
} private void prepare()
{
if(mThreadLocakMsgQueue.get()!=null)
{
throw new RuntimeException("message queue should only be one for pre thread");
}
mThreadLocakMsgQueue.set(new MessageQueue());
onPrepared();
} public MessageQueue getMessageQueue()
{
return mThreadLocakMsgQueue.get();
} public void quit()
{
synchronized (objsync) {
mQuite = true;
getMessageQueue().quit();
}
} protected void onPrepared()
{ }
}

MessageHandlerThread

如上,我们定义了一个MessageHandlerThread。

关键的run方法:

    public void run() {
TraceLog.d("MessageHandlerThread start running");
prepare();
final MessageQueue mQueue = getMessageQueue();
while(true)
{
synchronized (objsync) {
if(mQuite)
{
TraceLog.i("quite msg queue");
break;
}
}
Message msg = mQueue.next();
TraceLog.i("get next msg:"+msg);
if(msg == null)
{
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchHandlerMessage(msg);
} TraceLog.i("thread is done");
}

while(true) ,是的,消息机制一直在运行着,知道quit的时候。

首先是preopare();里面有个变量

ThreadLocal<MessageQueue> mThreadLocakMsgQueue = new ThreadLocal<MessageQueue>();

这是一个特殊的变量,也就是说每个线程拥有一方实例,且,各个线程之间的变量是不可见的。

这样我们保证了,每个messagequeue与thread对应。

接下来我们看看MsgHandler,也就是“操作者”

package com.joyfulmath.androidstudy.thread.messagemachine;

import com.joyfulmath.androidstudy.TraceLog;

public abstract class MsgHandler {
/*
* message queue is only one in thread
* */
final MessageQueue mQueue; public MsgHandler(MessageQueue mQueue)
{
this.mQueue = mQueue;
} public void dispatchHandlerMessage(Message msg)
{
TraceLog.i();
onHandleMessage(msg);
} public void sendMessage(Message msg)
{
enqueueMessage(msg,0L);
} private boolean enqueueMessage(Message msg, long when)
{
msg.target = this;
return mQueue.enqueueMessage(msg, 0);
} protected abstract void onHandleMessage(Message msg);
}

其实handler主要任务是2个,把消息加入队列,异步执行消息操作。

protected abstract void onHandleMessage(Message msg);

这个虚函数就是说,每个handler都需要自己去 “handler”自己发送的消息。

public class Message {
public MsgHandler target;
public int what;
@Override
public String toString() {
return "message:"+what;
} }

最后是message类,只有很简单的2个变量,第一个是在dispatchmessage的时候,知道派送给那个handler来处理。

第二个是消息区分的标志,当然也可以添加其他的一些变量。

以上就是一个简单的消息机制的代码。所以我们总结下消息机制大概需要这么几个角色。

1.消息

2.消息队列

3.thread,也就是消息机制运行的载体

4.handler,也就是“操作者”。

其实根据《android 进程/线程管理(一)----消息机制的框架》,

android消息机制也与上面类似,当然在细节上,android代码的思想的光辉可以看出来。

所以下面将着重分析android消息系统各个精彩的细节,关于系统框架的介绍,可以看本系列的其他文章。

一下源码分析,是基于andorid4.4的,其他版本的源码可能会有不同,请注意。

我们首先来看MessageQueue,andorid的MQ不是一个队列,居然是一个链表!

使用链表的原因应该是,我们不知道queue的长度大小,理论上是足够大,只要内存允许的话。

还有一个重要原因是:

void removeMessages(Handler h, int what, Object object)
void removeMessages(Handler h, Runnable r, Object object)

它可以快速的删除我们不需要的message。

我们来看messagequeue入列和出列操作:

boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
} synchronized (this) {
if (mQuitting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
} 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;
}
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
} // We can assume mPtr != 0 because the loop is obviously still running.
// The looper will not call this method after the loop quits.
nativePollOnce(mPtr, nextPollTimeoutMillis); 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 (false) Log.v("MessageQueue", "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
} // Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
} // If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
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);
} // Run the idle handlers.
// We only ever reach this code block during the first iteration.
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("MessageQueue", "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;
}
}

入列操作:首先是对一些情况的判断,是否设置了handler,是否已经开始退出消息机制等。

然后是把queue加入队列。这些基本可以理解为是同步的,也就是不会block,应为这个操作有极大的可能运行在主线程。

而next恰恰是messagequeue设计的精髓。

nativePollOnce(mPtr, nextPollTimeoutMillis);

线程将CPU交给其他线程运行,自己进入一个等待状态。出发时机就是,timeout或者等待的事件发生了。

所以这个函数是next方法实现等到新消息到来的关键。应此我们可以回答在第一篇里我们提出的那个问题?

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

一开始队列是空的,但是next方法会block住,不会返回null,只有当设置了quit flag以后,才会返回null。

我们看到的enqueueMessage里面的nativeWake就是叫醒这个地方的。

接下去就是取得消息,或者消息时间还没有到,就在此进入等待状态。

当然如果有idehandler需要执行的话,可以执行。

本文实现了一个自定义的消息机制,以及分析了android messagequeue的源码。

关于handler,looper的进一步分析将在下一篇中介绍。

android 进程/线程管理(四)----消息机制的思考(自定义消息机制)的更多相关文章

  1. android 进程&sol;线程管理(四)续----消息机制的思考(自定义消息机制)

    继续分析handler 和looper 先看看handler的 public void dispatchMessage(Message msg) { if (msg.callback != null) ...

  2. android 进程&sol;线程管理(一)----消息机制的框架

    一:android 进程和线程 进程是程序运行的一个实例.android通过4大主件,弱化了进程的概念,尤其是在app层面,基本不需要关系进程间的通信等问题. 但是程序的本质没有变,尤其是多任务系统, ...

  3. android 进程&sol;线程管理(二)----关于线程的迷思

    一:进程和线程的由来 进程是计算机科技发展的过程的产物. 最早计算机发明出来,是为了解决数学计算而发明的.每解决一个问题,就要打纸带,也就是打点. 后来人们发现可以批量的设置命令,由计算机读取这些命令 ...

  4. android 进程&sol;线程管理(三)----Thread&comma;Looper &sol; HandlerThread &sol; IntentService

    Thread,Looper的组合是非常常见的组合方式. Looper可以是和线程绑定的,或者是main looper的一个引用. 下面看看具体app层的使用. 首先定义thread: package ...

  5. android 进程间通信 messenger 是什么 binder 跟 aidl 区别 intent 进程间 通讯? android 消息机制 进程间 android 进程间 可以用 handler么 messenger 与 handler 机制 messenger 机制 是不是 就是 handler 机制 或 , 是不是就是 消息机制 android messenge

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha messenger 是什么 binder 跟 aidl 区别 intent 进程间 通讯 ...

  6. android学习-进程&sol;线程管理-完整

    我们知道,应用程序的主入口都是main函数--"它是一切事物的起源" main函数工作也是千篇一律的, 初始化 比如ui的初始化,向系统申请资源等. 进入死循环 再循环中处理各种事 ...

  7. python进阶------进程线程(四)

    Python中的协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到其 ...

  8. ucore操作系统学习&lpar;四&rpar; ucore lab4内核线程管理

    1. ucore lab4介绍 什么是进程? 现代操作系统为了满足人们对于多道编程的需求,希望在计算机系统上能并发的同时运行多个程序,且彼此间互相不干扰.当一个程序受制于等待I/O完成等事件时,可以让 ...

  9. 【朝花夕拾】Android性能篇之(六)Android进程管理机制

    前言        Android系统与其他操作系统有个很不一样的地方,就是其他操作系统尽可能移除不再活动的进程,从而尽可能保证多的内存空间,而Android系统却是反其道而行之,尽可能保留进程.An ...

随机推荐

  1. springmvc&plus;spring&plus;mybatis&plus;maven项目集成shiro进行用户权限控制【转】

    项目结构:   1.maven项目的pom中引入shiro所需的jar包依赖关系 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ...

  2. HQL查询语言——转载(http&colon;&sol;&sol;www&period;cnblogs&period;com&sol;20gg-com&sol;p&sol;6045739&period;html)

    Hibernate查询语言(HQL)是一种面向对象的查询语言,类似于SQL,但不是对表和列操作,HQL适用于持久对象和它们的属性. HQL查询由Hibernate转换成传统的SQL查询,这在圈上的数据 ...

  3. 【Git】笔记3

    来源:廖雪峰 远程仓库 远程仓库采用github 准备工作:创建远程仓库 1.创建一个github账号 2.在本地设置ssh,获取/home/user/.ssh/id_rsa.pub内容 3.在git ...

  4. Spring3中的mvc&colon;interceptors标签配置拦截器

    mvc:interceptors 这个标签用于注册一个自定义拦截器或者是WebRequestInterceptors. 可以通过定义URL来进行路径请求拦截,可以做到较为细粒度的拦截控制. 例如在配置 ...

  5. 翻译:Angular 2 - TypeScript 5 分钟快速入门

    原文地址:https://angular.io/docs/ts/latest/quickstart.html Angular 2 终于发布了 beta 版.这意味着正式版应该很快就要发布了. 让我们使 ...

  6. linux内存管理机制

    物理内存和虚拟内存 我们知道,直接从物理内存读写数据要比从硬盘读写数据要快的多,因此,我们希望所有数据的读取和写入都在内存完成,而内存是有限的,这样就引出了物理内存与虚拟内存的概念. 物理内存就是系统 ...

  7. 让ASP&period;NET MVC页面返回不同类型的内容

    在ASP.NET MVC的controller中大部分方法返回的都是ActionResult,更确切的是ViewResult.它返回了一个View,一般情况下是一个HTML页面.但是在某些情况下我们可 ...

  8. to&lowbar;date&lpar;&rpar;与to&lowbar;char&lpar;&rpar;

    1.以时间(Date类型)为查询条件时,可以用to_date函数实现: select t.* from D101 t where t.d101_40 = to_date('2013/9/12', 'y ...

  9. mysql必知必会系列&lpar;一&rpar;

    mysql必知必会系列是本人在读<mysql必知必会>中的笔记,方便自己以后查看. MySQL. Oracle以及Microsoft SQL Server等数据库是基于客户机-服务器的数据 ...

  10. effective java学习笔记之不可实例化的类

    在没有显式声明一个类的构造方法时,编译器会生成默认的无参构造方法,在设计工具类时,我们通常将方法设置成静态方法,以类名.方法名的形式调用,此时这个类就没有必要创建实例,我们知道抽象类不可以被实例化,但 ...