Java Object.wait() & Object.notify() 使用示例

69 阅读1分钟

Object.wait:施放对象锁、同时当前线程进入等待队列

Object.notify:唤醒第一个等待线程

package com.test.root.thread;

/**
 * Object.wait() & Object.notify() 使用示例
 */
public class WaitAndNotifyExample {

    private final Object lock = new Object();
    private boolean isGetNeedResource = false;

    private class WaitThread extends Thread {
        @Override
        public void run() {
            System.out.println("WaitThread 等待拿锁");
            synchronized (lock) {
                System.out.println("WaitThread 拿到锁");
                while (!isGetNeedResource) {
                    try {
                        System.out.println("WaitThread 未取得必要资源,施放锁并等待处理");
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("WaitThread 收到通知后继续执行");
                }
                System.out.println("WaitThread 获取到必要资源,逻辑处理完成");
            }
        }
    }

    public class NotifyThread extends Thread {
        @Override
        public void run() {
            System.out.println("NotifyThread 等待拿锁");
            synchronized (lock) {
                System.out.println("NotifyThread 拿到锁");
                isGetNeedResource = true;
                System.out.println("NotifyThread 将资源置为可以使用");
                lock.notify();
                System.out.println("通知 WaitThread 线程");
            }
        }
    }

    public void runWaitThread(){
        new WaitThread().start();
    }

    public void runNotifyThread(){
        new NotifyThread().start();
    }

    public static void main(String[] args) {
        WaitAndNotifyExample t = new WaitAndNotifyExample();
        t.runWaitThread();
        t.runNotifyThread();
    }

}

提示:notify会唤醒一个等待线程,但是并不会施放对象锁,需要等待 synchronized 代码块执行完毕后才释放