The general idea is that two (multiple) threads share a storage area, and they operate this memory concurrently.
The following is a simulation program that I initially wrote. If you need it, contact me QQ402320131 ~ :
Here, only Hander, HandlerThread, and Looper2 are attached.
Package com. zte. liu;
Public class Handler {
Private Looper2 logoff = null;
Public Handler (Looper2 looper ){
This. logoff = logoff;
}
Public Message obtainMessage (){
Return new Message (this );
}
Public Message obtainMessage (int id ){
Return new Message (id, this );
}
Public void dispatchMsg (Message msg ){
HandleMessage (msg );
}
Public Looper2 getLooper (){
Return logoff;
}
Public void handleMessage (Message msg) {// Hook Function
System. out. println (msg. getId ());
}
}
Public class HandlerThread implements Runnable {
Public void run (){
Looper2.prepare ();
Looper2.loop ();
}
}
Package com. zte. liu;
Public class Looper2 {
Private static Looper2 loop = null;
Private MessageQueue <Message> mQueue;
Private Looper2 (){
MQueue = new MessageQueue ();
}
Public static void prepare (){
If (logoff = null ){
Loop = new Looper2 ();
} Www.2cto.com
}
Public static Looper2 myloop (){
Prepare ();
Return logoff;
}
Public MessageQueue <Message> getQueue (){
Return mQueue;
}
Public static final void loop (){
System. out. println ("loop begin ...");
Looper2 loop = myloop ();
MessageQueue <Message> queue = logoff. mQueue;
If (logoff = null ){
Return;
}
While (true ){
System. out. println ("---- queue size =" + queue. size ());
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
Message msg = (Message) queue. next ();
If (msg! = Null ){
If (msg. getHandler () = null) return;
Else {
Msg. getHandler (). dispatchMsg (msg );
Message. recycle (msg );
}
}
}
}
}
From: liuyangsyouxiang Column