Though my question sound like stupid..
Here is code for multiple thread :
public class Main {
private int x = -1;
public Main(int xy) {
this.setX(xy);
}
static Main main;
public static void main(String[] args) {
main = new Main(10);
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (main) {
System.out.println(Thread.currentThread().getName());
for (int i = 0; i < 5; i++) {
main.setX(main.getX() + 10);
if (main.getX() >= 40) {
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println("X : " + main.getX());
}
}
}
};
Thread one = new Thread(runnable);
one.setName("Hi From One!!");
one.start();
Thread two = new Thread(runnable);
two.setName("Hi From Two!!");
two.start();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
While executing this code I am getting following output:
Hi From Two!!<br>
X : 20<br>
X : 30<br>
Exception in thread "Hi From Two!!" java.lang.IllegalMonitorStateException<br>
at java.lang.Object.wait(Native Method)<br>
at java.lang.Object.wait(Object.java:503)<br>
at Main$1.run(Main.java:23)<br>
at java.lang.Thread.run(Thread.java:722)<br>
Hi From One!!<br>
Exception in thread "Hi From One!!" java.lang.IllegalMonitorStateException<br>
at java.lang.Object.wait(Native Method)<br>
at java.lang.Object.wait(Object.java:503)<br>
at Main$1.run(Main.java:23)<br>
at java.lang.Thread.run(Thread.java:722)<br>
I am not getting why it is throwing the IllegalMonitorStateException
.
Here what I am trying to achieve is I want if value of X is grater than 40 same thread should wait and let other to execute.
Thanks, Yash