先上代码:
//主线程的handler
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
System.out.println("this is response from main thread " + Thread.currentThread().getId());
handler2.sendEmptyMessage(0);
}};
//线程1handler
private Handler handler1;
//线程2handler
private Handler handler2;
//子线程1
private Thread thread1 = new Thread(){
@Override
public void run()
{
super.run();
//子线程中实现handler必须先调用Looper.prepare();否则会抛出异常
Looper.prepare();handler1 = new Handler()//这里也可以使用Handler(Looper.mylooper())
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
// mHandler.sendEmptyMessage(0);//向主线程发消息
// handler2.sendEmptyMessage(0);//线程2发消息
}
};
//启动子线程的消息循环队列
Looper.loop();}
};
//子线程2
private Thread thread2 = new Thread(){
@Override
public void run()
{
super.run();
Looper.prepare();
handler2 = new Handler()
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
handler1.sendEmptyMessage(0);//线程1发消息
System.out.println("this is response from handler2 in thread2 " + Thread.currentThread().getId());
}
};
Looper.loop();
}
};
测试代码:thread1.start();
thread2.start();
mHandler.sendEmptyMessage(0);
打印结果
I/System.out(26814): this is response from main thread 1
I/System.out(26814): this is response from handler2 in thread28050
I/System.out(26814): this is response from handler1 in thread18049