Помогите разобраться с кодом (notify,wait)

Я хочу сделать так что б сообщения из потоков выводились поочередно, через цикл, все что у меня получилось это вот:

class Q {
    boolean peredano = false;

    synchronized void client() {
        while (peredano) {
            for (int i = 0; i < 5; i++) {
                System.out.println("Получено: " + i);
                System.out.println("In method \"Client\": " + Thread.currentThread().getName());
                peredano = false;
                Thread.currentThread().notify();
            }

        }
    }

    synchronized void postavchik() {
        while (!peredano) {
            for (int i = 0; i < 5; i++) {
                System.out.println("Отправлено: " + i);
                System.out.println("In method \"postavchik\": " + Thread.currentThread().getName());
                peredano = true;

                try {
                    Thread.currentThread().wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            }
        }
    }

    class myThreads extends Thread {
        Q q;

        myThreads(String nameThread, Q q) {
            super(nameThread);
            this.q = q;
            start();
        }


        @Override
        public void run() {
            while (true) {
                q.client();
            }
        }
    }

    class twoThread extends Thread {
        Q q;

        twoThread(String nameThread, Q q) {
            super(nameThread);
            this.q = q;
            start();
        }

        @Override
        public void run() {
            while (true) {
                q.postavchik();
            }
        }

    }

    public class Java {
        public static void main(String[] args) {
            Q q = new Q();
            myThreads one = new myThreads("one", q);
            twoThread two = new twoThread("two", q);
        }
    }

Выводит:

Отправлено: 0
In method "postavchik": two
Получено: 0
In method "Client": one
Exception in thread "two" Exception in thread "one" java.lang.IllegalMonitorStateException
    at java.lang.Object.notify(Native Method)
    at Q.client(Java.java:10)
    at myThreads.run(Java.java:46)
java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:502)
    at Q.postavchik(Java.java:24)
    at twoThread.run(Java.java:63)

Я начинающий и буду рад любому совету, упреку чему либо


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