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");
}
}
java笔记之wait和notify的深入理解
最新推荐文章于 2024-05-24 07:48:46 发布