我知道有很多类似的问题,但没有人帮助我。 当我得到 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/