gpt4 book ai didi

java - 处理程序的 `handleMessage` 返回主线程的线程 ID 而不是工作线程的线程 ID

转载 作者:行者123 更新时间:2023-11-29 23:12:54 27 4
gpt4 key购买 nike

我正在尝试掌握 Android 中的多线程。我的目标是将数据从主线程发送到工作线程。

我在其 onCreate 中有一个包含以下代码的主要 Activity -

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ThreadOne threadOne = new ThreadOne();
threadOne.start();
threadOneLooper = threadOne.getLooper();

Message msg = new Message();
msg.obj = "message.";

Log.i("id--(threadOneLooper)", String.valueOf(threadOneLooper.getThread().getId()));
Log.i("id--(Main)", String.valueOf(getMainLooper().getThread().getId()));

TestHandler mHandler = new TestHandler(threadOneLooper);
mHandler.handleMessage(msg);
}

如您所见,我在 threadOneLooper 中存储了工作线程循环程序的引用,然后记录了其关联线程的 ID。同时我也打印了主线程的id。

以下是我的线程的代码 -

public class ThreadOne extends Thread{

@Override
public void run() {

if (Looper.myLooper() == null)
Looper.prepare();

Log.i("ThreadOne", "run()");

// Just making sure all approaches give the same result
Log.i("Id--Thread id 1", String.valueOf(getLooper().getThread().getId()));
Log.i("Id--Thread id 2", String.valueOf(getId()));

Looper.loop();
}

Looper getLooper() {
if (Looper.myLooper() != null)
return Looper.myLooper();
else
return null;
}

下面是我的处理程序的代码-

public class TestHandler extends Handler {

TestHandler(Looper myLooper) {
super(myLooper);
}
public void handleMessage(Message msg) {

String txt = (String) msg.obj;
Log.i("Handler", txt);
Log.i("Id--(Handler)", String.valueOf(getLooper().getThread().getId()));
}
}

现在,问题是我假设 Log.i("Id--(Handler)", String.valueOf(getLooper().getThread().getId())); 语句将记录 ThreadOne 的线程 ID,因为我们将线程的循环程序传递给处理程序。但是,被记录的 id 是主线程的。这是为什么?假设 handleMessage() 正在主线程上执行是否正确?

最佳答案

问题出在 ThreadOnegetLooper() 方法上。该方法返回 myLooper()与调用该方法的线程关联。

为了返回与 ThreadOne 关联的 Looper,我建议类的以下实现:

public class ThreadOne extends Thread {
private Looper mLooper = null;

@Override
public void run() {
Looper.prepare();
mLooper = Looper.myLooper();

Looper.loop();
}

Looper getLooper() {
return mLooper;
}
}

注意! ThreadOneLooper 在运行之前为 null。您不能更早地获得对它的非 null 引用。你必须 check if the thread is running在调用 getLooper() 方法之前。

附言您可能需要重新考虑获取 ThreadOneLooper 的方法。拥有一个与 ThreadOne 关联的 Handler 可能就足够了 ( see the example of thread )。

关于java - 处理程序的 `handleMessage` 返回主线程的线程 ID 而不是工作线程的线程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55781681/

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