gpt4 book ai didi

java - 在线程的构造函数中调用 Looper.prepare() 会导致 RunTimeException

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:28 26 4
gpt4 key购买 nike

我有一个,它扩展到Thread,如下 -

public class ThreadTest extends Thread {

private Handler handler;
private Runnable runnable;

public ThreadTest(Runnable runnable, Handler handler) {

this.handler = handler;
this.runnable = runnable;
}

@Override
public void run() {
super.run();

Message msg = handler.obtainMessage();
msg.obj = "YUSSSSSS!";
handler.sendMessage(msg);

if (Looper.myLooper() != null) {
Looper.myLooper().quit();
Log.i("Looper", "has been quit");
}

}
}

现在,我希望将一个looper附加到该线程。根据我对 Looper 的理解,默认情况下只有主线程会附加一个 looper

我尝试从 ThreadTest 类的构造函数中调用 Looper.prepare()Looper.loop(),如下所示 -

public ThreadTest(Runnable runnable, Handler handler) {

Looper.prepare();

this.handler = handler;
this.runnable = runnable;

Looper.loop();
}

但是,我在 Looper.prepare(); 处得到 java.lang.RuntimeException: Only one Looper may be create per thread 异常。

虽然,如果我在 Run() 中附加 looper,我不会遇到任何问题。

我做错了什么?

最佳答案

每个线程都有一个循环器,并且只有一个循环器,在尝试向线程添加循环器之前需要进行检查。

您还需要在构造函数中添加 if (Looper.myLooper() != null) {} 。请记住,如果在线程构造函数中调用looper.myLooper(),则只能获取主线程Looper。因为此时新线程还没有构造出来。

关于java - 在线程的构造函数中调用 Looper.prepare() 会导致 RunTimeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46432044/

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