Android Handler机制的分析

我们在分析Handler之前,先看一下Handler它的作用,它的使用的场景。Android源码关于Handler的描述是这样的:

/**
 * A Handler allows you to send and process  Message and Runnable
 * objects associated with a thread's MessageQueue.  Each Handler
 * instance is associated with a single thread and that thread's message
 * queue.  When you create a new Handler, it is bound to the thread /
 * message queue of the thread that is creating it -- from that point on,
 * it will deliver messages and runnables to that message queue and execute
 * them as they come out of the message queue.
 * 
 * There are two main uses for a Handler: (1) to schedule messages and
 * runnables to be executed as some point in the future; and (2) to enqueue
 * an action to be performed on a different thread than your own.
 * /

Hadler简单来说就是向一个线程的消息队列(MessageQueue)中发送Message 和 Runnable对象,并在相关的线程中处理这些Message 和 Runnable。

1. 当前线程可以向自己的消息队列中发送Message 和 Runnable,并设定这些对象被执行的时间

2. 异步的线程可以通过Handler向与该Handler对应的线程中发送Message和Runnable,并在该线程中执行。当我们在子线程中获取到数据需要更新到界面时就可以通过Handler向主线程中发送消息。

了解了Handler的作用,我们想一下Android系统为什么要引入Handler,它的原理是什么?

我们在开发中都会用到多线程,会涉及到多线程间的通信。我们在实现多线程间的通信的时候比较常见的方式实际上就是通过共享内存的方式,我们通过两个线程对同一个变量的访问可以实现线程间的通信。但是这种方式我们在实现的时候需要考虑线程的同步,我们需要自己去实现这些机制。

Android系统引入的Handler实际上是对线程间通信的一种封装,通过消息队列,帮我们很好的实现了线程间的通信。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值