java笔记之wait和notify的深入理解

package com.lyzx.concurrent.lock;

/**
 * 测试wait和Notify的笔记,在看读写锁源码时的感想,
 * 当很多线程在一个对象上等待时,调用该对象的notifyAll方法
 * 这是所有在这个对象上等待的线程都会被"唤醒",注意这里的唤醒不是指
 * 立即执行,而是进入了可执行队列等待获取锁,此时,调用notifyAll()的方法出了
 * 方法体后就释放了锁,这个时候很多等待的线程开始争抢这个锁,当争抢到就执行自己的代码,
 * 执行完后放弃锁由其他等待线程争抢锁并执行,注意这个过程各个等待线程是互斥的
 */
public class WaitNotifyTest {
    public static void main(String[] args) {
        WN wn = new WN();

        for(int i=0;i<10 ;i++){
            new Thread(()-> {
                try {wn.lock();}catch(InterruptedException e){}
            },"A"+i).start();
        }

        try {
            Thread.sleep(3000);
            wn.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class WN{
    private volatile int flag = 0;

    public synchronized void lock() throws InterruptedException {
        String name = Thread.currentThread().getName();
        System.out.println(name+"_lock() start");
        while(flag == 0){
            System.out.println(name+" 在睡觉");
            wait();
            Thread.sleep(500);
            System.out.println(name + " 睡醒了");
        }
        System.out.println(name+"_lock() end");
    }

    public synchronized void unlock() throws InterruptedException{
        System.out.println(Thread.currentThread().getName()+"_unlock() start");
        ++flag;
        notifyAll();
        System.out.println(Thread.currentThread().getName()+"_unlock() end");
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值