如何让一个线程在Android中成功等待?

b5lpy0ml  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(425)

我启动了2个线程来接收不同页面(A和B)中的消息,但无法让一个wait成功。
下面是receiveMsg线程的代码。

//BufferedReader brClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
private class receiveMsg implements Runnable {
    @Override
    public void run() {
        try {
            String data;
            while ((data = brClient.readLine()) != null) {
                // diffent operations to fit page A and B
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

当切换页面(A -〉B)时,我试图让A中的一个线程等待,以避免与B中的另一个线程竞争相同的消息。

// page A
@Override
public void onPause() {
    super.onPause();
    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> onPause");
    try {
        receiveMsgThread.wait();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

才发现一个例外

java.lang.RuntimeException: Unable to pause activity {com.example.chat/com.example.chat.B_Container_Activity}: java.lang.IllegalMonitorStateException: object not locked by thread before wait()

我在StackOverflow中找到了一个solution,但它在我的项目中不起作用。

synchronized(receiveMsgThread) {
    try {
        receiveMsgThread.wait();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

“不工作”意味着没有例外,但当点击A中的按钮并尝试切换页面(A -〉B)时,应用程序卡住。

I/System.out: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> onPause
I/ZrHungImpl: sendRawEvent. wpId = 257
E/HiView.HiEvent: length is 0 or exceed MAX: 1024
I/om.example.cha: Thread[7,tid=21291,WaitingInMainSignalCatcherLoop,Thread*=0x7b849a5c00,peer=0x16644030,"Signal Catcher"]: reacting to signal 3
I/om.example.cha: 
I/om.example.cha: Wrote stack traces to tombstoned
I/ZrHungImpl: sendRawEvent. wpId = 258
E/HiView.HiEvent: length is 0 or exceed MAX: 1024
zlwx9yxi

zlwx9yxi1#

你不需要。你从不等待主线程。尝试这样做会导致用户界面没有响应,系统弹出窗口告诉用户你的应用没有响应。它甚至会导致看门狗跳闸,你的应用被ANR杀死。相反,让它在后台运行,如果需要的话,在结果完成之前打开一个加载屏幕。
另外,wait()也不是这样使用的。在Java中,Wait与并发锁定有关。每个对象都有一个wait函数,它与线程无关。它不等待线程完成。你可以使用join来完成这个任务。但是你仍然不应该在主线程上调用join。

相关问题