我有一个类 extends HandlerThread
,它看起来像这样:
public class MyHandlerThread extends HandlerThread {
private Object lock;
//constructor
public MyHandlerThread() {
super(“MyHandlerThread”);
lock = new Object();
}
public void prepare() {
//starts the handler thread
start();
//Wait for thread starting
Log.d(TAG, "wait for thread starting…");
synchronized (lock) {
try {
lock.wait(5000);
} catch (InterruptedException e) {
Log.e(TAG, "Failed to wait for thread to start");
}
}
//WHY getLooper() returns null here?
if(getLooper() == null) {
Log.d("GET LOOPER NULL!");
}
}
@Override
public void run() {
Log.d("run() begin...");
initializeSomeObjects()
Log.d(“initialise objects done!”);
//Notify that run() finished
synchronized (lock) {
lock.notify();
}
Log.d("run() end!”);
}
}
如上所示,该prepare()
函数启动线程并等待run()
完成,然后尝试获取 looper。
在另一个类中,我创建了一个MyHandlerThread
& 启动它的实例:
MyHandlerThread myThread = new MyHandlerThread();
myThread.prepare();
控制台中显示的日志:
wait for thread starting…
run() begin...
initialise objects done!
run() end!
GET LOOPER NULL!
为什么在函数中,尽管线程已经启动(已执行)prepare()
,但调用getLooper()
返回null ?run()