Java 中的线程同步,IllegalMonitorStateException
我正在尝试同步两个线程 - “主”线程和一个可运行线程。我收到 IllegalMonitorStateException,但我不完全理解“您没有对象的锁”的含义。
这是我的代码:
public class ThreadsTest {
private static ThreadsTest instance;
public volatile boolean flag = false;
public void doStuff() {
System.out.println("first");
this.flag = true;
}
public Runnable mDrawer = new Runnable() {
public void run() {
synchronized (ThreadsTest.getInstance()) {
while (flag == false)
try {
wait();
} catch (InterruptedException ie) {
System.out.println("second");
}
}
}
};
public static ThreadsTest getInstance() {
if (ThreadsTest.instance == null) {
ThreadsTest.instance = new ThreadsTest();
}
return ThreadsTest.instance;
}
private ThreadsTest() {
}
public static void main(String[] args) {
ThreadsTest t = ThreadsTest.getInstance();
t.mDrawer.run();
t.doStuff();
}
}
I am trying to synchronize two threads - the "Main" thread, and a runnable. I get the IllegalMonitorStateException, but I do not completelty understand what "you do not have the lock of the object" means.
Here is my code:
public class ThreadsTest {
private static ThreadsTest instance;
public volatile boolean flag = false;
public void doStuff() {
System.out.println("first");
this.flag = true;
}
public Runnable mDrawer = new Runnable() {
public void run() {
synchronized (ThreadsTest.getInstance()) {
while (flag == false)
try {
wait();
} catch (InterruptedException ie) {
System.out.println("second");
}
}
}
};
public static ThreadsTest getInstance() {
if (ThreadsTest.instance == null) {
ThreadsTest.instance = new ThreadsTest();
}
return ThreadsTest.instance;
}
private ThreadsTest() {
}
public static void main(String[] args) {
ThreadsTest t = ThreadsTest.getInstance();
t.mDrawer.run();
t.doStuff();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只能在同步的对象上调用
wait()
方法。因此,由于您已同步 (ThreadsTest.getInstance()),因此必须编写 ThreadsTest.getInstance().wait()。
不确定您要在这里测试什么,如果它只是基本的线程同步示例,那么您应该将代码更改为
You may call
wait()
method only on objects you synchronizing on.So, since you have
synchronized (ThreadsTest.getInstance())
, you must writeThreadsTest.getInstance().wait()
.Not sure what you trying to test here exactly, if it's just basic thread sync sample, then you should change your code to