Print odd and even numbers using multithreading

I am trying to learn Multi threading and for practice, I am trying to print an odd and even number using two threads. I created an object that will act as a lock for both threads. When I try to execute it, it throws java.lang.IllegalMonitorStateException.

class EVENODDimpl implements Runnable {
    int num;
    int temp = 0;
    Object lock = new Object();

    public EVENODDimpl( int num) {
        this.num = num;
    }

    public void run() {
        try {
            synchronized (lock) {
                while(temp<num) {
                    temp++;
                    System.out.println(Thread.currentThread().getName()+"   "+temp);
                    this.notify();
                    this.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } 
    }
}

The main method:

public class EVENODD {
    public static void main(String[] args) {
        int i = 10;
        EVENODDimpl ei = new EVENODDimpl(i);
        Thread t1 = new Thread( ei,"EvenThread");
        Thread t2 = new Thread( ei,"OddThread");
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
+4
source share
3 answers

You waitand notifyon this, but you have waitand notifyon lock, because you synchronize on lock, you can not wait, and notifyon a different object than the one on which you are synchronized, working version:

class EVENODDimpl implements Runnable {
    int num;
    int temp = 0;
    Object lock = new Object();

    public EVENODDimpl( int num) {
        this.num = num;
    }

    public void run() {
        try {
            synchronized (lock) {
                while(temp<num) {
                    temp++;
                    System.out.println(Thread.currentThread().getName()+"   "+temp);
                    lock.notify();
                    lock.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } 
    }
}
+3
source

javadoc

, , , , .

, notify wait . , , , , . this . . lock .

- , .

+3

java.lang.IllegalMonitorStateException - , this.notify(), . synchronized (lock) : synchronized (this)

+1

Source: https://habr.com/ru/post/1684600/


All Articles