LooperExecutor简单注释

源码分析:

public class LooperExecutor extends Thread implements Executor {
	private static final String TAG = "LooperExecutor";
	// Object used to signal that looper thread has started and Handler instance
	// associated with looper thread has been allocated.
	// 对象表示循环线程已开始并用循环线程关联到已经分配的处理实例上
	private final Object looperStartedEvent = new Object();
	private Handler handler = null;
	private boolean running = false;
	private long threadId;

	@Override
	public void run() {
		Looper.prepare();
		synchronized (looperStartedEvent) {
			Log.d(TAG, "Looper thread started.");
			handler = new Handler(); 
			// 这里handler对象是实例化LooperExecutor对象所在线程的Handler
			threadId = Thread.currentThread().getId();
			looperStartedEvent.notify();//looperStartedEvent通知
		}
		Looper.loop();// 跳转到requestStart()中的looperStartedEvent.wait()后执行
	}

	public synchronized void requestStart() {
		if (running) {
			return;
		}
		running = true;
		handler = null;
		start();
		// Wait for Hander allocation.
		synchronized (looperStartedEvent) {
			while (handler == null) {
				try {
					looperStartedEvent.wait();//跳转到run()开始执行
				} catch (InterruptedException e) {
					Log.e(TAG, "Can not start looper thread");
					running = false;
				}
			}
		}
	}

	public synchronized void requestStop() {
		if (!running) {
			return;
		}
		running = false;
		// post到创建的线程结束Looper
		handler.post(new Runnable() {
			@Override
			public void run() {
				Looper.myLooper().quit();
				Log.d(TAG, "Looper thread finished.");
			}
		});
	}

	// Checks if current thread is a looper thread.
	public boolean checkOnLooperThread() {
		return (Thread.currentThread().getId() == threadId);
	}

	@Override
	public synchronized void execute(final Runnable runnable) {
		if (!running) {
			Log.w(TAG, "Running looper executor without calling requestStart()");
			return;
		}
		if (checkOnLooperThread()) {
			// 当前执行代码在创建LooperExecutor对象线程中,那就直接在当前线程执行
			runnable.run();
		} else {
			// 当前执行代码不在创建LooperExecutor对象线程中,那就post到创建LooperExecutor对象的线程中去执行
			handler.post(runnable);
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值