This is my first post so sorry if I do something wrong. I'm trying to understand how work the threads in Java, in particular the synchronization, that's why I created a little piece of code which is supposed to print 1, 2, 3, 4, 5, 6 (in one thread) and then a second thread wait that's the first finished and then print 6, 5, 4, 3, 2, 1 but it only do the first 6 steps and tell me that there is a monitor problem for the wait method in the thread t2 and a problem with the notify all of the thread t1. Maybe I haven't understood anything about the synchronization of an object. Here is my code :
public class anObject extends Thread {
long value;
String name;
public anObject(long value, String name) {
this.value = value;
this.name = name;
}
public synchronized void add() {
this.value++;
}
public synchronized void sub() {
this.value--;
}
public static void main(String[] args) {
anObject il = new anObject(0, "Bob");
synchronized (il) {
Thread t1 = new Thread(il) {
public void run() {
while (il.value > 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 6; i++) {
il.add();
System.out.println(il.value);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
il.notifyAll();
}
};
Thread t2 = new Thread(il) {
public void run() {
while (il.value < 6) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j < 6; j++) {
il.sub();
System.out.println(il.value);
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
il.notifyAll();
}
};
t1.start();
t2.start();
}
}
}
And this is what appeared in the terminal :
Exception in thread "Thread-2" 1
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at anObject$2.run(anObject.java:53)
2
3
4
5
6
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at anObject$1.run(anObject.java:45)
Thanks a lot for your help! Greetings