我正在尝试同步两个线程-“主”线程和一个可运行线程。我得到了 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();
}
}