Главная

Java

Многопоточность




Wait and Notify :

*.wait() и *.notify() должны находится обязательно в synchronized методе иначе будет Exception





Пример :


public class WaitAndNotify {

    public static void main(String[] args) throws InterruptedException {
        MyTread myTread = new MyTread();
        myTread.start();
        synchronized (myTread) {
            myTread.wait();
        }
        System.out.println(myTread.getTotal());


    }

    static class MyTread extends Thread {
        private int total;

        public int getTotal() {
            return total;
        }

        @Override
        public void run() {
            synchronized (this) {
                for (int i = 0; i < 5; i++) {
                    total += i;
                    try {
                        sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                notify();
            }

        }
    }


}


Полезные ссылки: