In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the differences between Handler, Thread and HandlerThread in Android. It is very detailed and has certain reference value. Friends who are interested must finish reading it.
I. Prophase knowledge reserve
(1) Handler class, official document, Handler
Public class 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.
(2) Thread class, official document, Thread
Public class Thread. Extends Object implements Runnable.A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
(3) HandlerThread class, official document, HandlerThread
Public class HandlerThread. Extends Thread. Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start () must still be called.
The difference between the two and the three
① Handler: responsible for sending and processing messages in android, which enables message communication between other regional threads and the main thread.
The smallest unit in a ② Thread:Java process that performs operations, that is, the basic unit that performs processor scheduling. A program that runs separately in a process.
③ HandlerThread: HandlerThread,Android, a class that inherits from Thread, does not encapsulate Thread in Java, but provides a class HandlerThread that inherits from Thread, which encapsulates Java's Thread with many conveniences.
-I'm the dividing line-
In fact, the main focus of this problem is on the HandlerThread class, so what is the role of this class, and where is the so-called convenience encapsulation?
Observe two sentences in the official document of HandlerThread: ① Thread. Handy class for starting a new thread that has a looper. ② The looper can then be used to create handler classes.
Interpretation: after the HandlerThread object start, you can get its Looper object, and use this Looper object instance Handler, and then Handler can run in other threads.
-I'm the dividing line-
So what exactly is the relationship between Handler and Looper, and why does HandlerThread do this? Look at the following picture:
Andriod provides Handler and Looper to satisfy communication between threads. Handler first in, first out principle. The Looper class is used to manage the message exchange (MessageExchange) between objects within a particular thread.
1) Looper: a thread can generate a Looper object that manages the MessageQueue (message queue) in this thread and loops messages.
2) Handler: you can construct a Handler object to communicate with Looper so that push new messages can be sent to MessageQueue, or you can receive messages sent by Looper from MessageQueue.
3) Message Queue (message queue): used to store messages placed by threads.
4) Message: a message carrier for communication between threads. To transport goods between the two terminals, Message acts as a container, which can store any message you want to convey.
You can see why: if a thread wants to process a message, it must have its own Looper, not where the Handler is created.
Note: corresponding relation Thread (1): Looper (1): MessageQueen (1): Handler (n).
III. The use of HandlerThread
As mentioned earlier, when communicating between threads, such as updating UI, which is common in Android, it involves the communication between the child thread and the main thread, which is implemented by Handler+Looper, but you have to manipulate Looper manually, which is not recommended, so Google encapsulates the HandlerThread class (similar to the AsyncTask class).
On the code, the specific implementation:
Public class MainActivity extends AppCompatActivity {Handler mainHandler,workHandler; HandlerThread mHandlerThread; TextView text; Button button1,button2; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); text = (TextView) findViewById (R.id.text1); / / create Handler mainHandler = new Handler () associated with the main thread / * * step ①: create HandlerThread instance object * pass parameter = thread name, function = mark the thread * / mHandlerThread = new HandlerThread ("handlerThread"); / * step ②: start the thread * / mHandlerThread.start () / * step ③: create worker thread Handler & copy handleMessage () * function: associate the Looper object of HandlerThread, Implement the message handling operation & communicate with other threads * Note: the execution thread of the message processing operation (HandlerMessage ()) = the worker thread created by mHandlerThread executes * / workHandler = new Handler (mHandlerThread.getLooper ()) {@ Override public void handleMessage (Message msg) {/ / sets two message cancellation operations Identify switch (msg.what) {case 1: try {/ / delay operation Thread.sleep (1000) by msg } catch (InterruptedException e) {e.printStackTrace () } / / UI update operation mainHandler.post (new Runnable () {@ Override public void run () {) in the main thread through the Handler.post method of the main thread Text.setText ("first execution") }}); break; case 2: try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace () } mainHandler.post (new Runnable () {@ Override public void run () {text.setText ("second execution");}}) Break; default: break;} / * * step ④: use the worker thread Handler to send messages to the worker thread's message queue * in the worker thread, fetch the corresponding message when the message loop & perform the relevant operation on the worker thread * / button1 = (Button) findViewById (R.id.button1) Button1.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {Message msg = Message.obtain (); msg.what = 1; / / the identity of the message msg.obj = "A" / / message storage / / send a message to its bound message queue workHandler.sendMessage (msg) via Handler;}}); button2 = (Button) findViewById (R.id.button2) Button2.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {Message msg = Message.obtain (); msg.what = 2; msg.obj = "B"; workHandler.sendMessage (msg);}}) } @ Override protected void onDestroy () {super.onDestroy (); mHandlerThread.quit (); / / exit the message loop workHandler.removeCallbacks (null); / / prevent Handler memory leaks to empty the message queue}}
As you can see from the above code, HandlerThread inherits from Thread, so it is essentially a Thread. The difference with ordinary Thread is that the implementation of Looper is then directly implemented internally, which is essential to the Handler messaging mechanism. With our own looper, we can distribute and process messages on our own threads. If you don't use HandlerThread, you need to call the Looper.prepare () and Looper.loop () methods manually.
/ create a new Handler in the child thread without using HandlerThreadnew Thread () {@ Override public void run () {Looper.prepare (); Hnadler handler = new Handler (); Looper.loop ();}}
Provide some other Android message mechanism analysis to help readers understand:
① Handler is the upper interface of the Android message mechanism, through which you can easily switch a task to the thread in which the Handler is located, which can be either the main thread or a child thread, depending on where the Looper passed in in the constructor used when constructing the Handler is located
The operation of ② Handler needs the support of the underlying MessageQueue and Looper. When Handler is created, it uses the Looper of the current thread to construct the message circulation system, and the thread does not have Looper by default. If you need to use Handler, you must create a Looper for the thread.
③ the first Handler-mainHandler in the above code, when instantiating, new the instance directly in the onCreate () method. In fact, it is already in the main thread. The Looper is initialized when the main thread-ActivityThread,ActivityThread is created, which is why Handler can be used directly by default in the main thread.
④ the second Handler-workHandler in the above code, when instantiating, the parameter is passed in mHandlerThread.getLooper (). Note that this Handler does not use the Looper of the main thread, but that the Looper,HandlerThread of the child thread can get the Looper of the child thread after calling the start () method, and then pass it into the constructor of the workHandler, then the workHandler will run in the child thread to handle the time-consuming operation.
How ⑤ Handler works: when Handler is created, it uses the Looper of the current thread to build the internal message circulation system. If the current thread does not have Looper, it will report an error "can't create handler inside thread that has not called Looper.prepare ()". There are two solutions: create Looper for the current thread, like workHandler in the above code, or create Handler in a thread with Looper, just like mainHandler in the above code.
⑥ calls the post method of Handler to post a Runnable to the Looper within Handler for processing, or you can send a message through the send method of Handler, which is also processed in Looper. In fact, the post method is finally accomplished through the send method. Whenever Looper finds a new message coming, it processes the message, and the run method of Runnable or the handleMessage method of Handler in the final message is called. Note that the Looper runs in the thread where the Handler was created, so that the business logic in the Handler is switched to the thread in which the Handler was created to execute
How ⑦ Looper works: Looper acts as a message loop in Android's message mechanism, specifically, it constantly checks MessageQueue for new messages and processes them immediately, otherwise it will remain blocked. Pay attention to some important Looper methods:
Looper.prepare ()-creates a Looper for the current thread
Looper.loop ()-turns on the message loop, and only when this method is called will the message loop system start the loop
Looper.prepareMainLooper ()-create a Looper for the main thread, that is, ActivityThread
Looper.getMainLooper ()-the Looper of the main thread can be obtained anywhere through this method
Looper.quit () Looper.quitSafely ()-exit Looper. Self-created Looper is recommended to exit when not in use.
⑧ ActivityThread main thread communicates between processes through ApplicationThread and AMS
The above is all the contents of the article "what are the differences between Handler, Thread and HandlerThread in Android". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.