1. Communication between child threads and sub-threads
Package Lib.com.myapplication;import Android.os.bundle;import Android.os.handler;import android.os.Looper;import Android.os.message;import Android.support.v7.app.appcompatactivity;public class Mainactivity extends appcompatactivity {private Handler handler1; Private Handler Handler2; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); New MyThread1 (). Start (); New MyThread2 (). Start (); } class MyThread1 extends Thread {@Override public void run () {super.run (); Looper.prepare (); Handler1 = new Handler () {@Override public void Handlemessage (Message msg) { Super.handlemessage (msg); System.out.println ("threadname--" + thread.currentthread (). GetName () + "messagewhat-" + msg.what); } }; try {Sleep (3000); } catch (Interruptedexception e) {e.printstacktrace (); } handler2.sendemptymessage (2); Looper.loop (); }} class MyThread2 extends Thread {@Override public void run () {super.run (); Looper.prepare (); Handler2 = new Handler () {@Override public void Handlemessage (Message msg) { Super.handlemessage (msg); System.out.println ("threadname--" + thread.currentthread (). GetName () + "messagewhat-" + msg.what); } }; try {sleep (4000); } catch (Interruptedexception e) {e.printstacktrace (); } handler1.sendemptymessage (5); Looper.loop (); } }}
Attention:
1. Call the method of the Looper class to prepare()
create a message loop for the current thread, calling the loop()
method to process the information until the loop ends.
2. Handler has several construction overloads that, if constructed without a Looper class object parameter, gets the Looper object of the current thread , which is the message loop of the current thread as the handler association.
3. in the message processing mechanism, the message is stored in a message queue, and the thread enters an infinite loop around the queue until the program exits.
If there is a message in the queue, the thread will take the message out and distribute it to the appropriate handler for processing;
If there is no message in the queue, the thread enters the idle wait state and waits for the next message to arrive.
Simple use of Android Handler and loops