需要在synchronized同步块的内部使用wait()和notify()方法

wait()和notify()方法不在synchronized同步块的内部使用会抛出异常:java.lang.IllegalMonitorStateException

wait()和notify()方法的使用示例

public class WaitNotifyDemo {
    static Object locko = new Object();

    static class WaitTarget implements Runnable{

        public static void main(String[] args) throws InterruptedException {
            Thread waitThread = new Thread(new WaitTarget(),"wait thread");
            waitThread.start();
            Thread.sleep(1000);

            Thread notifyThread = new Thread(new NotifyTarget(),"notify thread");
            notifyThread.start();
        }

        @Override
        public void run() {
            synchronized (locko){
                System.out.println("启动等待。。。。。。。。");
                try {
                    locko.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("收到通知,当前线程继续执行。");
            }
        }
    }

    static class NotifyTarget implements Runnable{

        @Override
        public void run() {
            synchronized (locko){
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入任意指令:");
                System.out.println("收到指令:" + scanner.next());
                locko.notifyAll();
                System.out.println("发通知了,但线程还没有立马释放锁。");
            }
        }
    }
}

请添加图片描述

wait()方法的原理

1、JVM会释放当前线程的对象锁监视器的Owner资格
2、JVM会将当前线程移入监视器的WaitSet队列
在当前线程执行wait()方法前,必须通过synchronized()方法成为对象锁的监视器的Owner

notify()方法的原理

JVM从对象锁的监视器的WaitSet队列移动一个线程到其EntryList队列。
在执行notify()方法前,当前线程也必须通过synchronized()方法成为对象锁的监视器的Owner

《Java高并发核心编程(卷2)》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值