等待/通知机制:wait/notify

wait-notify简介:

等待/通知机制:wait/notify_第1张图片

程序测试:

public class WaitNotify {
    static boolean flag = true;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread waitThread = new Thread(new Wait(), "waitThread");
        waitThread.start();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread notifyThread = new Thread(new Notify(), "notifyThread");
        notifyThread.start();
    }

    static class Wait implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                while (flag) {
                    System.out.println(Thread.currentThread() + " flag is true. release lock and wait@ " + LocalDateTime.now());
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread() + " flag is false. return@ " + LocalDateTime.now());
            }
        }
    }

    static class Notify implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                    System.out.println(Thread.currentThread() + " hold lock. notify @ " + LocalDateTime.now());
                    lock.notifyAll();
                    flag = false;
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " hold lock again. notify @ " + LocalDateTime.now());
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

测试结果:

Thread[waitThread,5,main] flag is true.release lock and wait@2017-03-10T11:05:56.710
Thread[notifyThread,5,main] hold lock. notify @ 2017-03-10T11:05:58.584
Thread[notifyThread,5,main] hold lock again. notify @ 2017-03-10T11:06:03.584
Thread[waitThread,5,main] flag is false. return@ 2017-03-10T11:06:08.584

运行过程原理:

等待/通知机制:wait/notify_第2张图片

原理说明:

  1. 使用wait()、notify()和notifyAll时需要先对对象加锁,否则会报异常:“java.lang.IllegalMonitorStateException”
  2. 调用wait()方法后,程序状态由running变为waiting,并将当前线程放置到对象的等待队列
  3. notify()或notifyAll()方法返回后,等待线程依旧不会从wait返回,需要调用notfiy()或notifyAll的线程释放锁以后,等待线程才【有机会】从wait返回
  4. notify()将等待队列中的一个线程从“等待队列”中移到“同步队列”中,而notifyAll方法则将等待队列中的所有线程全部移到“同步队列“中,被移动的线程由waiting变为blocked
  5. 从wait()方法返回的前提是获得调用对象的锁,由程序的打印结果可以证实

从上述细节可看出,等待/通知依托于同步机制,目的就是确保等待线程从wait()方法返回时,能够感知通知线程对变量做的修改

摘录:《Java并发编程的艺术》

你可能感兴趣的:(多线程)