2

我有一个类 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()

4

1 回答 1

4

HandlerThread Looper在 中初始化HandlerThread#run()

如果您覆盖该方法并且不调用super.run(),则不会执行来自超类的初始化代码。

于 2015-10-08T18:43:08.013 回答