Detailed explanation of the use and principle of Android handlerthread

1、 Meaning of handlerthread

Handlerthread can create a new thread with looper. This looper can be used to create other handlers. (looper in the thread) it should be noted that when creating a new one, it needs to be called back.

2、 Usage of handlerthread

In general, we often use handler to update UI threads in child threads. That's because there is a looper loop in the main thread. What's the use of handlerthread to create a new child thread with looper?

It must be a time-consuming operation. For example, for real-time data update, we need to switch the displayed data every 10 seconds. If we put this long-time repeated call operation into the UI thread, it can be executed, but after more such operations, it is easy to make the UI thread get stuck or even crash.

So we must call these in the child thread. Handlerthread inherits from thread. Generally, it is suitable for scenarios that combine the advantages of thread and handler. It is suitable for situations that run in the background for a long time and will be called at intervals (or in appropriate cases), such as the real-time update mentioned above.

3、 Update the UI every 2 seconds

4、 Handlerthread principle

First, we can see that handlerthread inherits from thread, so the logic in run () is run in the child thread.

Next, there are two key methods, run () and getlooper (): you can see in run () that it is very simple to create looper and the logic to make looper work. What's the use of notifyall() in run() and wait() in getloop() when mloop is created? Because mLooper is created in a thread, and our handler is initialized by calling getLooper () in the UI thread. In other words, we must wait until mloop is created before we can return correctly. getLooper(); Wait(), notify() is to solve the synchronization problem of these two threads.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>