优化项目过程当中发现了一个很是Low的问题,整理一下。备忘:java
说问题以前先看下HandlerThread的定义android
一个封装了looper的线程: 异步
Looper用于封装了android线程中的消息循环。默认状况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程建立一个消息循环,调用Looper.loop()来使消息循环起做用。从消息队列里取消息。处理消息。ide
注:写在Looper.loop()以后的代码不会被立刻执行。当调用后mHandler.getLooper().quit()后。loop才会停止,其后的代码才干得以执行。函数
Looper对象经过MessageQueue来存放消息和事件。一个线程仅仅能有一个Looper。相应一个MessageQueue。oop
下面是Android API中的一个典型的Looper thread实现:post
//Handler不带參数的默认构造函数:new Handler()。其实是经过Looper.myLooper()来获取当前线程中的消息循环,
//而默认状况下。线程是没有消息循环的,因此要调用 Looper.prepare()来给线程建立消息循环,而后再经过。Looper.loop()来使消息循环起做用。优化
[java] view plaincopyui
另,Activity的MainUI线程默认是有消息队列的。this
因此在Activity中新建Handler时,不需要先调用Looper.prepare()。
那么遇到了有多Low的问题呢:
项目中重写了一个HandlerThread,而后定义了post方法。而后在主线程中例如如下实现:
AsyncHandler.post(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
// 一坨要异步运行的代码******
Looper.loop();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
那么明眼人一看就看出问题来了 ,这代码一跑异步代码确定运行不到啊。为啥呢。且看下prepare的实现:
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
So,简单,倒是问题~