[英]Exception in thread “main” java.lang.IllegalMonitorStateException
I am working with Thread
in Java
and i get following error - I don't understand why?! 我正在使用Java
Thread
,我得到以下错误 - 我不明白为什么?!
Code: 码:
import java.util.Random;
public class Test {
public static void main(String[] args) throws InterruptedException {
Vlakno sude = new Vlakno("myName"); // Vlakno = thread class
sude.start();
sude.wait(); // ERROR IS ON THIS LINE
}
}
class Vlakno extends Thread {
private boolean canIRun = true;
private final String name;
Vlakno(String name) {
this.name = name;
}
@Override
public void run() {
while (canIRun) {
// System.out.println("Name: " + name);
}
}
public void mojeStop() {
System.out.println("Thread "+name +" end...");
this.canIRun = false;
}
}
In order to deal with the IllegalMonitorStateException
, you must verify that all invocations of the wait method are taking place only when the calling thread owns the appropriate monitor. 为了处理IllegalMonitorStateException
,您必须验证只有在调用线程拥有适当的监视器时才会发生wait方法的所有调用。 The most simple solution is to enclose these calls inside synchronized
blocks. 最简单的解决方案是将这些调用封装在synchronized
块中。 The synchronization object that shall be invoked in the synchronized
statement is the one whose monitor must be acquired. 应在synchronized
语句中调用的同步对象是必须获取其监视器的同步对象。
synchronize (sude) {
sude.wait();
}
For more information and examples, take a look here . 有关更多信息和示例,请查看此处 。
From the Java Docs of Object.wait
来自Object.wait
的Java Docs
IllegalMonitorStateException - if the current thread is not the owner of the object's monitor. IllegalMonitorStateException - 如果当前线程不是对象监视器的所有者。
After the invocation sude.start();
调用sude.start();
you have two threads running: The current thread and the thread running sude
. 你有两个线程在运行:当前线程和运行sude
的线程。 The current thread is not the owner of the object's monitor. 当前线程不是对象监视器的所有者。
To ensure that you are the owner of the object's monitor do this: 要确保您是对象监视器的所有者,请执行以下操作:
synchronize (sude) {
sude.wait();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.