We normally send messages from the child thread to the main thread, and the main thread already does Looper for us by default, so we can simply “create a Handler object and one thread sends messages and the other receives messages”… Let’s start by saying what a Looper is. It is like a Looper of a MessageQueue. A Message queue has only one Looper and manages the entire Message queue. A Message queue can hold multiple messages and workers can have multiple handlers. The butler sends them to perform tasks after storing or retrieving messages to the message queue;

So the number of them is as follows: Looper: 1; MessageQueue (MessageQueue) : 1; Message: You can have more than one; Worker (Handler) : Can be multiple;

New Thread(new Runnable() {@suppressLint ("HandlerLeak") @override public void run() { Our main thread is sending messages to child threads, so we need to keep the child thread immortal /** * 1. The Looper object is created, and MessageQueue * 2 is created in the Looper object. ThreadLocal */ looper.prepare (); ThreadLocal */ looper.prepare (); SubHandler = new Handler(){@override public void handleMessage(@nonnull MSG){if (msg.what==2) { Toast.maketext (mainactivity.this, "main thread: "+ msg.obj.tostring (), toast.length_short).show(); }}}; mLooper = Looper.myLooper(); /** * 1. Find the previously created Looper object from the current thread and then find MessageQueue * 2. */ looper.loop (); */ looper.loop (); Log.d(TAG, "run: loop() finished "); } }).start();Copy the code

@override protected void onDestroy() {super.ondestroy (); if (mLooper! =null) { mLooper.quit(); }}Copy the code

Reference: blog.csdn.net/iblade/arti…