java - 非法监控状态异常 : object not locked by thread before wait()

标签 java android multithreading wait java-threads

我知道有很多类似的问题,但没有人帮助我。 当我得到 IllegalMonitorStateException: object not locked by thread before wait() 时尝试暂停线程。

这是我的初始化方法:

// called only once in constructor; the variables are global ( private Thread ... )
    public void init() {

        recordingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                isNewRecordingThread= false;
                record();
            }
        });

        recognitionThread = new Thread(new Runnable() {
            @Override
            public void run() {
                isNewRecognition= false;
                recognize();
            }
        });
...
}

开始录制方法:

private synchronized void startRecording(Thread recordingThread) {
    if(isNewRecordingThread){
        recordingThread.start();
        return;
    }
    recordingThread.notify();
}

开始识别方法:

private synchronized void startRecognition(Thread recognitionThread) {
    shouldContinueRecognition = true;
    if(isNewRecognition){
        recognitionThread.start();
        return;
    }
    recognitionThread.notify();
}

以及我实际得到错误的停止方法:

private synchronized void stopRecordingAndRecognition(Thread recordingThread, Thread recognitionThread) {
    try{
        if (recordingThread != null && recordingThread.isAlive()) {
            recordingThread.wait();
        }
        if (recognitionThread != null && recognitionThread.isAlive()) {
            recognitionThread.wait();
        }
    } catch (InterruptedException e){
        Log.d("TESTING","InterruptedException e= "+e);
    }
}

最佳答案

“对象在 wait() 之前未被线程锁定”

想一想,这条消息中指的是什么对象? wait() 应用的那个对象:

recordingThread.wait();

recordingThread

synchronized void stopRecordingAndRecognition 是无关紧要的,因为它锁定了 this 对象,而不是 recordingThread

所以,有两种解决方案:

  • 强制方法在 recordingThread 上同步
  • 将同步方法嵌入到recordingThread类中

关于java - 非法监控状态异常 : object not locked by thread before wait(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50491166/

相关文章:

java - 过滤列表的组件

android - 我没有使用 Firebase 手机身份验证获取验证码

android - 如何检查 Intent/Activity 是否已在 Android 中打开?

android - 将图像发送到android中的URL

C++11 <thread> 使用 OpenGL 进行多线程渲染可防止主线程读取标准输入

java - JSR303 : Is it possible to inject arguments to a custom validator at validation time?

java - android splitting with space 不适用于这种情况。为什么?

multithreading - 提供多少逻辑处理器的运行时API是什么?

java - 如何使用 OnClickListener 检查当前选择了哪个 TextView(三个)

.net - 为什么 WCF ServiceHost 一旦超出范围仍保持打开状态?