Java中的线程同步,IllegalMonitorStateException [英] Threads synchronizing in Java, IllegalMonitorStateException
问题描述
我正在尝试同步两个线程-主"线程和一个可运行线程.我得到了IllegalMonitorStateException,但是我不完全理解您没有对象的锁"的含义.
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.
这是我的代码:
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();
}
}
推荐答案
您只能在同步对象上调用wait()
方法.
因此,由于您具有synchronized (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 write ThreadsTest.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
public class ThreadsTest {
private static ThreadsTest instance;
public volatile boolean flag = false;
public void doStuff() {
System.out.println("first");
this.flag = true;
synchronized (getInstance()) {
getInstance().notifyAll();
}
}
public Runnable mDrawer = new Runnable() {
public void run() {
synchronized (ThreadsTest.getInstance()) {
while (flag == false)
try {
ThreadsTest.getInstance().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) throws InterruptedException {
ThreadsTest t = ThreadsTest.getInstance();
new Thread(t.mDrawer).start();
Thread.sleep(1000L); // let other thread start, so it won't skip our notify()
t.doStuff();
}
}
这篇关于Java中的线程同步,IllegalMonitorStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!