1

I start 2 threads to receive messages in different pages (A and B) but cannot let one wait successfully.

Here is the code of the receiveMsg thread.

//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();
        }
    }
}

When switching pages (A -> B), I tried to let one thread in A wait to avoid competing for the same message with the other in B.

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

only to find a exception

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()

and I found a solution in the StackOverflow but it didn't work in my project.

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

"didn't work" means there is no exception but the App is stucked when clicking the button in A and trying to swithing pages (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

1 Answer 1

1

You don't. You NEVER wait on the main thread. Attempting to do so will cause an unresponsive UI and a system popup telling the user your app is unresponsive. It can even cause a watchdog to trip and your app to be killed with an ANR. Instead, let it run in the background and put up a loading screen if you need to until the result is done.

Also, that's not how you use wait(). Wait in Java has to do with concurrency locking. Every object has a wait function, it has nothing to do with threads. It doesn't wait for a thread to be done. You use join for that. But you should still never call join on the main thread.

Not the answer you're looking for? Browse other questions tagged or ask your own question.