0

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

1
  • It's thrown from wait. Have you looked up the javadoc to see when wait throws such an exception? Commented Apr 18, 2014 at 15:17

2 Answers 2

0

wait is a function that requires that the calling thread holds the monitor on the target.

In your case, you are calling this.wait(), but do not hold the monitor on this.

you need to either

synchronized (this) { wait(); } 

or

main.wait(); 
Sign up to request clarification or add additional context in comments.

Comments

0

The call of object.wait must synchronized on object.

You have called runnable.wait but synchronized on main.

Try main.wait();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.