android生产者消费者模式,生产者和消费者模式在Android中的应用

What

所谓生产者消费者模式,就是一个地方无脑生产,一个地方无脑消费,通过一个中间缓冲区建立的一种模式。这样的解耦是不是很多人所向往的,而解耦的关键是如何使用中间的缓冲区。生活中的例子也有很多,像卖手机的,他们只负责生产,而我们只负责消费,中间的缓冲区便是他们的库存。再比如邮局,我们只负责写信,收信人只负责收信,中间的缓冲区便是邮局。还有,坐地铁,上班打卡。。。生活中处处充满着这个模型。

3ad28eccd6f9

生产者和消费者模型

有了生产和消费,但是世界永远唯一不变的是变化,于是就产生了各种问题,生产者和消费者的量不一致,时间的把控,效率的高低,都是问题出现的因素。在美丽的大Android中很多地方也运用到了这个模型,同样的,也会出现这个问题,那么Android中是如何处理这些问题的呢?他的缓冲区是如何做的呢?

How

首先,看看Android中常用到这个模型的有哪些应用?

曾经面试的问题,Android中有几种方式可以在子线程中更新UI?

初学者看到这里,应该会自豪的说:

1,runOnUiThread

2,view.post()

3,handler

3ad28eccd6f9

runOnUiThread

3ad28eccd6f9

view.post()

前两种方式的源码 其内部都实现了mHandler.post(action)方法,说明这三种方式其实,就是一种方式,通过Handler机制实现,关于Handler机制实现,请听下回分解。

另外还有最熟悉的Toast

3ad28eccd6f9

Toast内部源码

其内部也是Handler:mHandler.obtainMessage(0, windowToken).sendToTarget();

Why

内部的实现都是Hander机制,其实Android消息机制的核心便是Handler机制,而实现消息机制模型就是生产者消费者模型。那么,Handler机制是如何实现的呢?

查看源码一路追踪,拨开层层迷雾,可以在MessageQueue,Message中查看得到生产者消费者模型的影子,Message就是生产出来的事物,而MessageQueue实现了生产和消费操作功能。

MeesageQueue,具体查看代码如下:

enqueueMessage()

boolean enqueueMessage(Message msg, long when) {

if (msg.target == null) {

throw new IllegalArgumentException("Message must have a target.");

}

if (msg.isInUse()) {

throw new IllegalStateException(msg + " This message is already in use.");

}

synchronized (this) {

if (mQuitting) {

IllegalStateException e = new IllegalStateException(

msg.target + " sending message to a Handler on a dead thread");

Log.w(TAG, e.getMessage(), e);

msg.recycle();

return false;

}

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;

}

next()

Message next() {

// Return here if the message loop has already quit and been disposed.

// This can happen if the application tries to restart a looper after quit

// which is not supported.

final long ptr = mPtr;

if (ptr == 0) {

return null;

}

int pendingIdleHandlerCount = -1; // -1 only during first iteration

int nextPollTimeoutMillis = 0;

for (;;) {

if (nextPollTimeoutMillis != 0) {

Binder.flushPendingCommands();

}

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;

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;

}

} 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(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;

}

分析如下:

生产物

3ad28eccd6f9

Message链表.png

生产者:

enqueueMessage() 生产的对象为Message

if(beforeMessag==null||when=0||when

initMessage;

}else{//新消息,是入队操作

prevMsg.next=curMsg;

}

Message p=Message mMessage;

Message prev;

loop //循环取出当前链表最后一个message,赋值给prev;

->prev =p;

->p=p.next;

//赋值给Next

msg.next=p=null;

prev.next =msg;

消费者:

next()

loop

->Message prevMsg=null; Message msg=mMessages;

//将下一个Msg上移,for loop 将剩下来的msg一一往前移动

-> if(prevMsg!=null) prevMsg.next=msg.next;

-> else mMessages=msg.next;// 主链表上移一个msg

-> return msg;

1,enqueueMessage() 为生产线程执行,入队一个Message ,return true。

2,next() 为消费线程执行,出队:在Looper.loop()中不断取, 而在next()中也是loop 只要取到了便return msg 否则wait。next加了一个同步锁,保证了与enqueue的互斥。enqueue 同样也添加了同步锁,从而保证了与next的互斥:将message添加到Message链表中去,判断,如果出现阻塞了,需要进行唤醒操作。妥妥的生产者消费者模型。

总结

生产者和消费者的精髓是:

不同线程操作同一对象的不同方法,但是要保持其互斥,也不能出现死锁的情况,条件满足就通知其他等待的线程 ,条件不满足,就休眠等待。

在Thread-1的生产者只负责生产,在Thread-2的消费者则只负责消费,操作互斥,当生产者达到上限则进行等待,反之消费者达到上限所有线程就等待。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值