模拟android Handler线程间通信

消息类:
package p;

public class Message {
	Runnable runnable;
	private long start;
	long delay;

	Handler target;

	public int arg;

	public Message(Handler target) {
		this.target = target;
		start = System.currentTimeMillis();
	}

	boolean canHandle() {
		return delay <= System.currentTimeMillis() - start;
	}
}
消息队列类:
package p;

import java.util.ArrayList;
import java.util.List;

public class MessageQueue {
	private List<Message> messages = new ArrayList<Message>();
	private int cursor = -1;

	/**
	 * 入队
	 * 
	 * @param message
	 */
	public void push(Message message) {
		messages.add(message);
	}

	/**
	 * 移出队列
	 * 
	 * @param message
	 */
	public void remove(Message message) {
		messages.remove(message);
		cursor--;
	}

	/**
	 * 出队
	 * 
	 * @return
	 */
	public Message pop() {
		Message message = null;
		if (!messages.isEmpty()) {
			message = messages.get(++cursor);
			if (cursor == messages.size() - 1) {
				cursor = -1;
			}
		}
		return message;
	}
}

Handler类:

package p;

public class Handler {
	private MessageQueue queue;

	public Handler() {
		queue = MessageManager.getMessageQueue();
		if (queue == null) {
			throw new RuntimeException(
					"创建Handler之前必须必须调用MessageManager.prepare()");
		}
	}

	/**
	 * 接收消息,子类去实现
	 * 
	 * @param message
	 */
	public void handleMessage(Message message) {
	}

	/**
	 * 发送消息
	 * 
	 * @param message
	 * @param delay
	 */
	public void sendMessage(Message message, long delay) {
		message.delay = delay;
		queue.push(message);
	}

	/**
	 * 发送任务
	 * 
	 * @param runnable
	 * @param delay
	 */
	public void post(Runnable runnable, long delay) {
		Message message = convertToMessage(runnable);
		message.delay = delay;
		queue.push(message);
	}

	/**
	 * 将任务转化为消息
	 * 
	 * @param runnable
	 * @return
	 */
	private Message convertToMessage(Runnable runnable) {
		Message message = new Message(this);
		message.runnable = runnable;
		return message;
	}

	/**
	 * 分派消息
	 * 
	 * @param message
	 */
	void dispatchMessage(Message message) {
		if (message.runnable != null) {
			message.runnable.run();
		} else {
			handleMessage(message);
		}
	}

}
消息管理类:
package p;

public class MessageManager {
	private static ThreadLocal<MessageQueue> local = new ThreadLocal<MessageQueue>();

	/**
	 * 获取消息队列
	 * 
	 * @return
	 */
	public static MessageQueue getMessageQueue() {
		return local.get();
	}

	/**
	 * 创建消息队列
	 */
	public static void prepare() {
		MessageQueue queue = local.get();
		if (queue != null) {
			throw new RuntimeException("每个线程只能有一个消息队列!");
		}
		local.set(new MessageQueue());
	}

	/**
	 * 开启消息循环
	 */
	public static void loop() {
		MessageQueue messageQueue = local.get();
		Message message;
		while (true) {
			if ((message = messageQueue.pop()) != null) {
				if (message.canHandle()) {
					messageQueue.remove(message);
					message.target.dispatchMessage(message);
				}
			}
		}
	}

}
模拟activity以及启动:
package p.client;

import p.Handler;
import p.Message;
import p.MessageManager;

public class UI2 {

	private Handler handler;

	public void onCreate() {
		System.out.println("onCreate:" + Thread.currentThread().getName());

		handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				System.out.println("handleMessage:"
						+ Thread.currentThread().getName());
				System.out.println(message.arg);
			}
		};

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(3000);
					System.out.println("sendMessage:"
							+ Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Message message = new Message(handler);
				message.arg = 10;
				handler.sendMessage(message, 3000);
			}
		}).start();

		System.out.println("End onCreate!");
	}

	public static void main(String[] args) {

		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				MessageManager.prepare();
				UI2 mainUI = new UI2();
				mainUI.onCreate();
				MessageManager.loop();
			}
		};

		Thread main = new Thread(runnable);
		main.setName("main");
		main.start();

	}
}
输出:
onCreate:main
End onCreate!
sendMessage:Thread-1
handleMessage:main
10


你可能感兴趣的:(模拟android Handler线程间通信)