【android】通过handle,looper实现多线程数据同步

代码如下:

public class MainActivity extends Activity {

private static final String TAG = "MainThread";
private Timer timer;
private TimerTask timerTask;
private Handler mMainHandle,mChildHandle;
private int i=0;

    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  timer = new Timer();
  timerTask = new MyTimerTask();
 
 
  mMainHandle = new Handler(){
   public void handleMessage(Message msg) {
    Log.e("mainhandle", i+"");
   }
  };
  new ChildThread().start();
  timer.schedule(timerTask, 0, 5000); 
    }
   
    public class MyTimerTask extends TimerTask{
  public void run() {
   if(mChildHandle!=null){
    Message childMsg = mChildHandle.obtainMessage();
    mChildHandle.sendMessage(childMsg);
    Log.e("thread", i+"");
   }
  }
    }
   
    public void onDestroy(){
     Log.i(TAG,"stop looping the child threads message queue");
     mChildHandle.getLooper().quit();
    }
   

class ChildThread extends Thread{
  public void run(){  
   Looper.prepare();
   mChildHandle = new Handler(){
    public void handleMessage(Message msg)
    {
     Log.i("child", "11111111");
     i++;   
     Message toMain = mMainHandle.obtainMessage();
     toMain.obj = this.getLooper().getThread().getName()+ i;
     mMainHandle.sendMessage(toMain);
     Log.i("i=",i+"");
    }
   };
   Looper.loop();  
  }
}
}



LOG如下:

08-16 08:08:12.936: ERROR/thread(235): 0
08-16 08:08:12.939: INFO/child(235): 11111111
08-16 08:08:12.939: INFO/i=(235): 1
08-16 08:08:12.939: ERROR/mainhandle(235): 1
08-16 08:08:13.239: DEBUG/dalvikvm(105): GC freed 2498 objects / 144872 bytes in 81ms
08-16 08:08:17.937: ERROR/thread(235): 1
08-16 08:08:17.940: INFO/child(235): 11111111
08-16 08:08:17.940: INFO/i=(235): 2
08-16 08:08:17.940: ERROR/mainhandle(235): 2
08-16 08:08:22.939: ERROR/thread(235): 2
08-16 08:08:22.939: INFO/child(235): 11111111
08-16 08:08:22.939: INFO/i=(235): 3
08-16 08:08:22.939: ERROR/mainhandle(235): 3
08-16 08:08:27.941: ERROR/thread(235): 3
08-16 08:08:27.941: INFO/child(235): 11111111
08-16 08:08:27.941: INFO/i=(235): 4
08-16 08:08:27.941: ERROR/mainhandle(235): 4
08-16 08:08:32.941: ERROR/thread(235): 4
08-16 08:08:32.941: INFO/child(235): 11111111
08-16 08:08:32.941: INFO/i=(235): 5
08-16 08:08:32.941: ERROR/mainhandle(235): 5
08-16 08:08:37.943: ERROR/thread(235): 5
08-16 08:08:37.943: INFO/child(235): 11111111
08-16 08:08:37.943: INFO/i=(235): 6
08-16 08:08:37.943: ERROR/mainhandle(235): 6
08-16 08:08:42.944: ERROR/thread(235): 6
。。。。。。







以上代码可以看出其执行的顺序。

转自http://www.eoeandroid.com/thread-29406-1-1.html

你可能感兴趣的:(多线程,thread,html,android)