Java多线程3:线程间通信-等待/通知机制(wait(),notify()&notifyAll())——学习方腾飞Java并发编程的艺术

等待/通知机制

等待/通知机制,是指线程A调用了对象O的wait()方法进入等待状态,而另外一个线程B调用了对象O的notify() or notifyAll()方法,线程A收到后从对象O的wait()方法返回,执行后续操作。线程间通过对象O来完成交互,对象上的notify(),notifyAll()如同信号一般,用来通知其他线程开始工作。
其中wait(),notify(),notifyAll()都是Object对象中的方法

public class MyThread04 {
    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        Thread aThread = new Thread(new aRunner(lock), "waitThread");
        Thread bThread = new Thread(new bRunner(lock), "notifyThread");
        aThread.start();
        Thread.sleep(3000);
        bThread.start();
    }

    static class aRunner implements Runnable {
        private Object lock;

        public aRunner(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + " begin at " + System.currentTimeMillis());
                    lock.wait();
                    System.out.println(Thread.currentThread().getName() + " end at " + System.currentTimeMillis());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class bRunner implements Runnable {
        private Object lock;

        public bRunner(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + " begin at " + System.currentTimeMillis());
                lock.notify();
                System.out.println(Thread.currentThread().getName() + " end at " + System.currentTimeMillis());

            }
        }
    }
}

// waitThread begin at 1533037521144
// notifyThread begin at 1533037524149
// notifyThread end at 1533037524150
// waitThread end at 1533037524151

注意细节

  1. 使用wait(),notify(),notifyAll()时需要先对调用对象加锁
  2. 调用wait()方法后,线程状态由RUNNING变为WAITING,并将当前线程放置到对象的等待队列
  3. notify()或notifyAll()方法调用后,等待线程不会从wait()返回,需要调用notify()或notifyAll()的线程释放锁之后,等待线程才有机会从wait()返回
  4. notify()方法将等待队列中的一个等待线程从其中移到同步队列中,而notifyAll()方法是将等待队列中所有的线程全部移到同步队列,被移动的线程状态从WAITING变为BLOCKED
  5. 从wait()方法返回的前提是获得了调用对象的锁。

猜你喜欢

转载自blog.csdn.net/qq_22798455/article/details/81319544