gpt4 book ai didi

android - getLooper() 启动 HandlerThread 后返回 null

转载 作者:行者123 更新时间:2023-12-05 00:22:02 29 4
gpt4 key购买 nike

我有一个类扩展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()返回 虽然线程已经启动( run() 被执行)?

最佳答案

HandlerThread LooperHandlerThread#run() 中初始化.

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

关于android - getLooper() 启动 HandlerThread 后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33020587/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com