communication between Android two sub-threadsTags: classthreadandroid sub-threading communication2015-03-20 17:03 3239 People read comments (0) favorite reports Classification:Personal Gossip
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
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!
[Java]View PlainCopy
- 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) {
- //handling messages here
- LOG.I ("Mthread", "received message:" +thread.currentthread (). GetName () +"----" +msg.obj);
- };
- };
- Looper.loop ();
- }
- }
[Java]View PlainCopy
- Public class Thread2 extends thread{
- @Override
- public Void Run () {
- For (int i=0; i<; i++) {
- Message msg = 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 (1000);
- }
- }
- }
Execution effect:
For full code download please see:
http://download.csdn.net/detail/kedaweiwei/8518701
(reprinted) communication between Android two sub-threads