用Java自己实现一个消息循环

作者: Jerry2015 | 来源:发表于2018-02-24 16:28 被阅读57次

ActivityThread类

public class ActivityThread {

    public static String currentThreadInfo() {
        Thread thread = Thread.currentThread();
        return "Thread id: " + thread.getId() + ", " + thread.toString();
    }

    public static void main(String[] args) {
        System.out.println(">>>onCreate");
        System.out.println("MainThread: " + currentThreadInfo());

        startTaskThread();

        Looper.prepareMainLooper();
        Looper.loop();
    }

    private static void startTaskThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        final long millis = (long) (2000 + Math.random() * 3000);
                        Thread.sleep(millis);
                        Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
                            @Override
                            public boolean handleMessage(Message msg) {
                                return false;
                            }
                        }) {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                            }
                        };
                        System.out.println();
                        System.out.println("Task " + millis + " Create In: " + currentThreadInfo());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                System.out.println("Task " + millis + " Run In: " + currentThreadInfo());
                            }
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

Handler类

public class Handler {
    final Looper mLooper;
    final MessageQueue mQueue;
    final Callback mCallback;

    public Handler() {
        this(Looper.myLooper());
    }

    public Handler(Looper looper) {
        this(looper, looper.mQueue, null);
    }

    public Handler(Looper looper, Callback callback) {
        this(looper, looper.mQueue, callback);
    }

    public Handler(Looper looper, MessageQueue queue, Callback callback) {
        mLooper = looper;
        mQueue = queue;
        mCallback = callback;
    }

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

    public final void sendMessage(Message msg) {
        msg.target = this;
        mQueue.enqueueMessage(msg);
    }

    public void handleMessage(Message msg) {
    }

    public interface Callback {
        boolean handleMessage(Message msg);
    }

    private static void handleCallback(Message message) {
        message.callback.run();
    }

    public final void post(Runnable runnable) {
        Message msg = new Message();
        msg.callback = runnable;
        sendMessage(msg);
    }
}

Looper类

public class Looper {
    private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();
    private static Looper sMainLooper;

    final MessageQueue mQueue = new MessageQueue();

    public static Looper getMainLooper() {
        return sMainLooper;
    }

    public static void prepareMainLooper() {
        prepare();
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

    public static Looper myLooper() {
        return sThreadLocal.get();
    }

    public static void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }

    public static void loop() {
        Looper looper = myLooper();
        for (; ; ) {
            Message msg = looper.mQueue.next();
            if (msg != null) {
                msg.target.dispatchMessage(msg);
            }
        }
    }
}

Message类

public class Message {
    public int what;
    public int arg1;
    public int arg2;

    Handler target;
    Runnable callback;

    @Override
    public String toString() {
        return "Message{" +
                "what=" + what +
                ", arg1=" + arg1 +
                ", arg2=" + arg2 +
                ", target=" + target +
                ", callback=" + callback +
                '}';
    }
}

MessageQueue类

import java.util.LinkedList;
import java.util.Queue;

public class MessageQueue {
    private final Queue<Message> mMessages = new LinkedList<>();

    public void enqueueMessage(Message msg) {
        synchronized (mMessages) {
            mMessages.add(msg);
            mMessages.notifyAll();
        }
    }

    public Message next() {
        synchronized (mMessages) {
            if (!mMessages.isEmpty()) {
                return mMessages.poll();
            }
            try {
                mMessages.wait();
                if (!mMessages.isEmpty()) {
                    return mMessages.poll();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return next();
    }
}

把上面几个类复制到一个Java工程里,运行ActivityThread的main方法即可。整体API跟Android的一致。通过wait和notify来避免死循环的性能问题,Android是通过MessageQueue.nativePollOnce Linux的epoll实现。但消息循环部分完全一致。

相关文章

网友评论

    本文标题:用Java自己实现一个消息循环

    本文链接:https://www.haomeiwen.com/subject/xwtcxftx.html