【发布时间】:2014-06-01 03:49:11
【问题描述】:
我看了生产者和消费者的例子,稍微改了一下。 Pro() 将打印“第一”,而 con() 将打印“第二”。我希望每个“第二”出现在“第一”之后。
public class test {
test() { }
synchronized void pro() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("First!");
notify();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
synchronized void con() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Second!");
notify();
}
}
}).start();
}
public static void main(String[] args) {
test m = new test();
m.pro();
m.con();
}
}
发生的错误是:
First!
Exception in thread "Thread-0" Exception in thread "Thread-1"
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at test$1.run(test.java:12)
at java.lang.Thread.run(Unknown Source)
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at test$2.run(test.java:32)
at java.lang.Thread.run(Unknown Source)
【问题讨论】:
-
@Java42 谢谢。我知道应该有“同步”,并且我已经在我的方法中添加了“同步”关键词。为什么还是错了?
-
更新您的问题,不要说“它不起作用”,而是说“我收到错误:”
。 -
@Sentimental 你的
run()方法应该同步,而不是pro()和con()方法。
标签: multithreading concurrency wait notify