在我开始使用Condition变量之前,我正试图理解对象等待原则。我写了一些代码来了解更多,但它没有按预期工作。
应该发生的是Waiter类等待线程启动。 同时,Notifier类使用循环将一些元素添加到列表中。一旦通知程序完成此操作,它会通知服务员应该只是打印它已被通知但我得到非法监控异常
这是我的输出
Exception in thread "Waiter Thread" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at tutorials.waitnotify.Waiter.run(Waiter.java:26)
at java.lang.Thread.run(Thread.java:745)
0 [Waiter Thread] DEBUG tutorials.waitnotify.Waiter - Starting waiter....
2002 [Notifier Thread] DEBUG tutorials.waitnotify.Waiter - Starting
notifier...
3005 [Notifier Thread] DEBUG tutorials.waitnotify.Waiter - Element added [1]
4007 [Notifier Thread] DEBUG tutorials.waitnotify.Waiter - Element added [2]
5012 [Notifier Thread] DEBUG tutorials.waitnotify.Waiter - Element added [3]
Exception in thread "Notifier Thread" java.lang.IllegalMonitorStateException
7022 [Notifier Thread] DEBUG tutorials.waitnotify.Waiter - Object about to
notify
at java.lang.Object.notify(Native Method)
at tutorials.waitnotify.Notifier.run(Notifier.java:42)
at java.lang.Thread.run(Thread.java:745)
这是代码 正如您所看到的,我正在尝试在公共锁定对象上进行同步。
public class Notifier implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Waiter.class);
private List<Integer> list;
private Object commonLock;
public Notifier(Object lock) {
this.list = new ArrayList<>();
this.commonLock = lock;
}
public void run() {
LOGGER.debug("Starting notifier....");
synchronized (commonLock) {
for (int i = 1; i <= 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
LOGGER.debug("Interrupted");
}
list.add(i);
LOGGER.debug("Element added [{}]", i);
}
LOGGER.debug("About to notify");
notify();
}
}
}
public class Waiter implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Waiter.class);
private final Object commonLock;
public Waiter(Object lock) {
this.commonLock = lock;
}
public void run() {
LOGGER.debug("Starting waiter....");
synchronized (commonLock) {
try {
wait(10000);
} catch (InterruptedException ie) {
LOGGER.debug("Interrupted");
}
}
LOGGER.debug("Object been notified");
}
}
public class WaiterNotifierMain {
public static void main(String[] args) {
BasicConfigurator.configure();
Object lock = new Object();
Waiter waiter = new Waiter(lock);
Notifier notifier = new Notifier(lock);
Thread waiterThread = new Thread(waiter);
Thread notifierThread = new Thread(notifier);
notifierThread.setName("Notifier Thread");
waiterThread.setName("Waiter Thread");
waiterThread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifierThread.start();
}
}
任何指针都将不胜感激。提前致谢
答案 0 :(得分:3)
你应该做
你得到一个例外,因为你正在等待并通知“这个”。你没有同步“这个”。
您可以考虑使用notifyAll()而不是notify():
如果您计划拥有多个Waiter线程,请记住notify()一次只能唤醒一个Waiter线程。如果要立即唤醒所有Waiter线程,则应使用notifyAll()方法。
即使知道你永远不会有多个Waiter线程,我认为最好使用notifyAll()而不是notify(),因为Notifier对象不知道有多少线程在监听对象。 ..