1 public class Thread1 extends Thread{ 2 private Handler handler1; 3 public Handler getHandler(){//注意哦,在run执行之前,返回的是null 4 return handler1; 5 } 6 @Override 7 public void run() { 8 9 Looper.prepare(); //为当前线程创建Looper 10 handler1 = new Handler(){ 11 public void handleMessage(android.os.Message msg) { 12 //这里处理消息 13 Log.i("MThread", "收到消息了:"+Thread.currentThread().getName()+"----"+msg.obj); 14 }; 15 }; 16 Looper.loop(); //开启循环 17 18 } 19 20 }
1 public class Thread2 extends Thread{ 2 @Override 3 public void run() { 4 5 for(int i=0; i<10; i++){ 6 Message msg = Message.obtain(); 7 msg.what = 1; 8 msg.obj = System.currentTimeMillis()+""; 9 handler1.sendMessage(msg); 10 Log.i("MThread", Thread.currentThread().getName()+"----发送了消息!"+msg.obj); 11 SystemClock.sleep(1000); 12 } 13 14 } 15 }