Android Knowledge Point 030 - Handler,Thread,HandlerThread

Handler
Handler is a mechanism introduced in Android that allows developers to participate in the processing of message loops in threads. Each Handler is associated with a thread, and each thread maintains a message queue MessageQueue, so that Handler is actually associated with a message queue.

The Message and Runnable objects can be sent to the MessageQueue (message queue) of the thread associated with the Handler through the Handler, and then the message queue has been cyclically taking out a Message, processing it, taking out the next Message after processing, and continuing Process, cycle over and over again.

When a Handler is created, the Handler is bound to the thread that currently creates the Handler. From then on, the Handler can send Message and Runnable objects to the message queue corresponding to the Handler. When a Message is taken out from the MessageQueue, the Handler will be asked to process it.

effect:

Handler can be used to communicate between multiple threads. Updating UI controls in the UI thread in another thread is just a typical case of using Handler. In addition, Handler can do many other things. Handler is the spokesperson of Thread and a bridge for communication between multiple threads. Through Handler, we can control another thread in one thread to do something.

 

Thread
thread, which can be regarded as an entity of a process, is the basic unit of CPU scheduling and dispatch. It is a basic unit smaller than a process that can run independently.

public class MyThread extends Thread{ @Override public void run(){ super.run(); // do something } } HandlerThread: encapsulates the internal principle of Handler + Thread = Thread class + Handler class mechanism, namely:
 

 

 

 

 


Quickly create a new worker thread with a Looper object by subclassing the Thread class

By encapsulating the Handler class, quickly create a Handler & communicate with other threads.

Internally calls Looper.prepare(); Looper.loop(); During the construction of the Looper object, a MessageQueue is initialized as a member variable of the Looper object.

The loop() is turned on, and the continuous loop takes messages from the MessageQueue for processing. When there is no message, it will block, and it will wake up when a message arrives.
———————————————
Copyright statement: This article is an original article by the CSDN blogger "Disciple Cat", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this copy for reprinting statement.
Original link: https://blog.csdn.net/github_37130188/article/details/89483199

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324090671&siteId=291194637