I've read the example of producer and consumer, and I changed a little. Pro() will print "first", and con() will print "second". I want every "second" appears after "first".
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();
}
}
The errors that occur are:
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)