当前位置:网站首页>Comics: how do you prove that sleep does not release the lock, and wait to release lock?
Comics: how do you prove that sleep does not release the lock, and wait to release lock?
2022-08-03 13:03:00 【Chinese community of Java】







wait 加锁示例
public class WaitDemo {
private static Object locker = new Object();
public static void main(String[] args) throws InterruptedException {
WaitDemo waitDemo = new WaitDemo();
// 启动新线程,To prevent the main thread was sleeping
new Thread(() -> {
try {
waitDemo.doWait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
Thread.sleep(200); // The trip itself has no meaning,是为了确保 wait() To perform again notify()
waitDemo.doNotify();
}
/**
* 执行 wait()
*/
private void doWait() throws InterruptedException {
synchronized (locker) {
System.out.println("wait start.");
locker.wait();
System.out.println("wait end.");
}
}
/**
* 执行 notify()
*/
private void doNotify() {
synchronized (locker) {
System.out.println("notify start.");
locker.notify();
System.out.println("notify end.");
}
}
}以上程序的执行结果为:
wait start.
notify start.
notify end.
wait end.
代码解析
从上述代码可以看出,我们给 wait() 和 notify() Two methods on the same lock(locker),But after the call wait() 方法之后 locker 锁就被释放了,The program to perform properly notify() 的代码,Because it is the same lock,如果不释放锁的话,是不会执行 notify() 的代码的,It can also be in the aftermath of the print confirmed(结果输出顺序),所以综合以上情况来说 wait() 方法是释放锁的.
sleep 加锁示例
public class WaitDemo {
private static Object locker = new Object();
public static void main(String[] args) throws InterruptedException {
WaitDemo waitDemo = new WaitDemo();
// 启动新线程,To prevent the main thread was sleeping
new Thread(() -> {
synchronized (locker) {
try {
System.out.println("sleep start.");
Thread.sleep(1000);
System.out.println("sleep end.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(200);
waitDemo.doNotify();
}
/**
* 执行 notify()
*/
private void doNotify() {
synchronized (locker) {
System.out.println("notify start.");
locker.notify();
System.out.println("notify end.");
}
}
}以上程序的执行结果为:
sleep start.
sleep end.
notify start.
notify end.
代码解析
从上述代码可以看出 sleep(1000) 方法(行号:11)执行之后,调用 notify() Methods do not get to locker 锁,从上述执行结果中可以看出,而是执行完 sleep(1000) Methods after execution of notify() 方法,Therefore can prove that call sleep() 方法并不会释放锁.
知识扩展
1.sleep 和 wait 有什么区别?
sleep 和 wait Almost all the interview will be asked questions,But want to completely correct answer seems to be not so simple.
对于 sleep 和 wait 的区别,The usual answer is that:
wait 必须搭配 synchronize 一起使用,而 sleep 不需要;
进入 wait The state of the thread to be notify 和 notifyAll 线程唤醒,而 sleep State of the thread cannot be notify 方法唤醒;
wait There are usually conditions to perform,Thread has been wait 状态,直到某个条件变为真,但是 sleep Just let your thread to sleep;
wait 方法会释放对象锁,但 sleep 方法不会.
But the above answer obviously missing an important difference,在调用 wait 方法之后,线程会变为 WATING 状态,而调用 sleep 方法之后,线程会变为 TIMED_WAITING 状态.
2.wait 能不能在 static 方法中使用?为什么?
不能,因为 wait 方法是实例方法(非 static 方法),因此不能在 static 中使用,源码如下:
public final void wait() throws InterruptedException {
wait(0);
}3.wait/notify 可以不搭配 synchronized 使用吗?为什么?
不行,Because don't match synchronized Use program will be an error,如下图所示:
The deeper reason is that do not add synchronized 的话会造成 Lost Wake-Up Problem,Wake up the leakage problems,详情可见:https://juejin.im/post/5e6a4d8a6fb9a07cd80f36d1
总结
本文我们通过 synchronized Lock the same object,来测试 wait 和 sleep 方法,By order of execution result proved that:wait 方法会释放锁,而 sleep 方法并不会.At the same time we also told a few wait 和 sleep 的常见面试问题,希望本文可以帮助到你.

往期推荐
边栏推荐
- How can I get a city's year-round weather data for free?Precipitation, temperature, humidity, solar radiation, etc.
- R语言使用zoo包中的rollapply函数以滚动的方式、窗口移动的方式将指定函数应用于时间序列、计算时间序列的滚动标准差(设置每个窗口不重叠)
- 基于php网上零食商店管理系统获取(php毕业设计)
- Grafana 高可用部署最佳实践
- 什么是分布式锁?几种分布式锁分别是怎么实现的?
- PolarFormer: Multi-camera 3D Object Detection with Polar Transformers 论文笔记
- 【Verilog】HDLBits题解——验证:阅读模拟
- 漫画:怎么证明sleep不释放锁,而wait释放锁?
- Win11怎么禁止软件后台运行?Win11系统禁止应用在后台运行的方法
- 使用 %Status 值
猜你喜欢
随机推荐
图像融合SDDGAN文章学习
An动画基础之散件动画原理与形状提示点
pandas连接oracle数据库并拉取表中数据到dataframe中、生成当前时间的时间戳数据、格式化为指定的格式(“%Y-%m-%d-%H-%M-%S“)并添加到csv文件名称中
基于php网上零食商店管理系统获取(php毕业设计)
899. 有序队列
【Verilog】HDLBits题解——验证:阅读模拟
技术分享 | 接口自动化测试如何搞定 json 响应断言?
Using the Work Queue Manager (4)
Nodejs 安装依赖cpnm时,install 出现Error: Cannot find module ‘fs/promises‘
awk入门教程
Image fusion SDDGAN article learning
特征工程学习笔记
使用工作队列管理器(四)
The common problems in the futures account summary
项目概述、推送和存储平台准备
nacos app
Image fusion DDcGAN study notes
Oracle安装完毕(系统盘),从系统盘转移到数据盘
Mysql重启后innodb和myisam插入的主键id变化总结
从零开始C语言精讲篇5:指针












