IllegalMonitorStateException при решении задачи на многопоточность - Java

Пытаюсь освоить многопоточность в Java на следующем примере: нужно решить, что было раньше -- курица или яйцо.
Есть сущность, которая слушает оппонентов, запущенных в отдельных потоках, и определяет результат.

Код:

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Dispute dispute = new Dispute();
        Chicken chicken = new Chicken(dispute);
        Egg egg = new Egg(dispute);
        Thread chickenT = new Thread(chicken);
        Thread eggT = new Thread(egg);

        chickenT.start();
        eggT.start();

        chickenT.join();
        eggT.join();
        System.out.println("first was " + dispute.word);
    }
}
class Dispute {
    String word;
    Dispute() {
        word = "";
    }

    public synchronized void say(String word) {
        notify();
        this.word = word;
        System.out.println(word);
        try {
            wait();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
class Chicken implements Runnable {
    Dispute dispute;
    Chicken(Dispute dispute) {
        this.dispute = dispute;
    }

    @Override
    public void run() {
        int i = 0;
        while (i < 10) {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            dispute.say("chicken");
            i++;
            synchronized (dispute.getClass()) {  // тут придумываю сам
                if (i == 10) notify();
            }
        }
    }
}
class Egg implements Runnable {
    Dispute dispute;
    Egg(Dispute dispute) {
        this.dispute = dispute;
    }

    @Override
    public void run() {
        int i = 0;
        while (i < 10) {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            dispute.say("egg");
            i++;
            synchronized (dispute.getClass()) { // здесь тоже
                if (i == 10) notify();
            }
        }
    }
}

Ошибка:

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException: current thread is not owner
  at java.base/java.lang.Object.notify(Native Method)
  at Chicken.run(Main.java:55)
  at java.base/java.lang.Thread.run(Thread.java:1583)

Я понимаю суть ошибки, но не знаю, как быть в такой ситуации, как разбудить поток.


Ответы (0 шт):