【发布时间】:2018-11-02 14:35:54
【问题描述】:
我知道有很多类似的问题,但没有人帮助我。当我尝试暂停线程时,我收到了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();
}
开始识别方法:
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()不是一个好主意,因为您可能会错过信号或出现虚假唤醒! -
任何想法如何使它更好?
-
@abrutsze 如果我们不知道您想要实现什么,我们如何才能做得更好。
-
目标是启动线程,暂停它并在恢复之后
-
@abrutsze 我添加了一个用于暂停/恢复线程的代码 sn-p。
标签: java android multithreading wait java-threads