我知道有很多类似的问题,但没有一个能帮助我。 当我尝试暂停线程时,我会得到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();
}
});
...
}
startRecording 方法:
private synchronized void startRecording(Thread recordingThread) {
if(isNewRecordingThread){
recordingThread.start();
return;
}
recordingThread.notify();
}
startRecognition方法:
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()/await()
,因为这样可能会错过信号或出现虚假唤醒! - Mokarrom Hossain