我们在分析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实际上是对线程间通信的一种封装,通过消息队列,帮我们很好的实现了线程间的通信。