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

maxx777
  • 1,320
  • 1
  • 20
  • 37
yash
  • 151
  • 1
  • 2
  • 11

2 Answers2

0

The call of object.wait must synchronized on object.

You have called runnable.wait but synchronized on main.

Try main.wait();

Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45
andy
  • 1,336
  • 9
  • 23
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();
njzk2
  • 38,969
  • 7
  • 69
  • 107