Android, believe that the main thread and the communication between the sub-threading everyone is not unfamiliar with it. In one interview experience, I was asked how two sub-threads communicated with each other. Hey, yo! This is a cover for me. Later went home to study the next, share to everyone.
In fact, the Android thread communication is nothing more than handler and Looper operation.
In general, communication between the main thread and the child thread is sent to the looper in the main thread through the message in the handler threads in the main course, or handler in the main thread sends a runnable through post to Looper. Looper is present in the main thread by default. What if there is no looper in the child thread? Very simply, we can bind looper to a child thread and create a handler. By sending a message through this handler in another thread, you can implement communication between the child threads.
public class Thread1 extends thread{ private Handler handler1; Public Handler GetHandler () {//Note oh, before run executes, the return is null return handler1; } @Override public Void Run () { looper.prepare (); Handler1 = new Handler () {public void Handlemessage (Android.os.Message msg) { //Here Processes message log.i ("Mthread", " Received the message: "+thread.currentthread (). GetName () +"----"+msg.obj) ;}; Looper.loop (); } }
public class Thread2 extends thread{ @Override public void Run () {for (int i=0; i<10; i++) { Message ms g = Message.obtain (); Msg.what = 1; Msg.obj = System.currenttimemillis () + ""; Handler1.sendmessage (msg); LOG.I ("Mthread", Thread.CurrentThread (). GetName () + "----sent a message! "+msg.obj); Systemclock.sleep (+);}}}
Execution effect:
For code download please see:
http://download.csdn.net/detail/kedaweiwei/8518701
Communication between Android two sub-threads