二.Android中Handler的模型

二.Android中Handler的模型_第1张图片
image.png

这里对ThreadLocal进行下说明.
Looper存取是通过ThreadLocal变量,这是为了方便开发者创建自己的消息循环系统,让两个子线程通信

如下实现了线程thread1向线程myThread发送消息

public class MyThread extends Thread {
    private Looper mLooper;

    @Override
    public void run() {
        super.run();
        Looper.prepare();//创建Looper放入ThreadLocal
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Looper.loop();//从ThreadLocal取出当前线程的Looper,开始消息循环
    }

    public Handler getHanlder(){
        return new Handler(mLooper);
    }

    public Looper getLooper() {
        return mLooper;
    }
}
class Test{
    void test(){
        MyThread myThread=new MyThread();
        Handler handler= new Handler(myThread.getLooper()){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what==0){

                }
            }
        };
        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                 Message message=new Message();
                 message.what=0;
                 handler.sendMessage(message);
            }
        });
    }
}

你可能感兴趣的:(二.Android中Handler的模型)