十八、ThreadLocal实战(模拟实现一个简单版本的Hand

2021-06-12  本文已影响0人  大虾啊啊啊

1、创建Looper类

 static class Lopper {
        static final ThreadLocal<Lopper> threadLocal = new ThreadLocal<Lopper>();
        private LinkedBlockingQueue<Message> msgQueue;
        public LinkedBlockingQueue<Message> getMsgQueue() {
            return msgQueue;
        }
        public Lopper() {
            msgQueue = new LinkedBlockingQueue<Message>();
        }
        public static void prepare() {
            if (threadLocal.get() == null) {
                threadLocal.set(new Lopper());
            }
        }
        public static Lopper myLooper() {
            return threadLocal.get();
        }

        public static void loop() {
            while (true) {
                LinkedBlockingQueue<Message> queue = Lopper.myLooper().getMsgQueue();
                if (queue != null && queue.size() > 0)
                {
                    try {
                        Message message = queue.take();
                        message.target.handleMessage(message);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

2、创建Handler类

 static class Handler {
        private Lopper lopper;

        /**
         * 在哪个线程创建Handler,
         * 就是拿哪个线程的Loopper
         */
        public Handler() {
            lopper = Lopper.myLooper();
        }

        public void handleMessage(Message message) {
        }

        public void sendMessage(Message message) {
            message.target = this;
            try {
                lopper.getMsgQueue().put(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

3、创建Message类

    static class Message {
        public Handler target;
        public Object content;
    }

4、测试

public static void main(String[] args) {
        final Lopper lopper = new Lopper();
        lopper.prepare();
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message message) {
                super.handleMessage(message);
                System.out.println("调用后的线程:" + Thread.currentThread().getName());
                System.out.println("接受消息:"+message.content);
            }
        };
        new Thread() {
            @Override
            public void run() {
                System.out.println("调用前的线程:" + Thread.currentThread().getName());
                Message message = new Message();
                message.content = "hello world";
                handler.sendMessage(message);
                System.out.println("发送消息:"+message.content);

            }
        }.start();

        try {
            Thread.sleep(200);
            lopper.loop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
调用前的线程:Thread-0
发送消息:hello world
调用后的线程:main
接受消息:hello world
上一篇下一篇

猜你喜欢

热点阅读