当前位置:网站首页>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
的常见面试问题,希望本文可以帮助到你.
往期推荐
边栏推荐
- 【R】用grafify搞定统计绘图、方差分析、干预比较等!
- 【Verilog】HDLBits题解——验证:阅读模拟
- 实数取整写入文件(C语言文件篇)
- 【必读要点】Pod控制器Deployment更新、回退详解
- The common problems in the futures account summary
- 期货开户中常见问题汇总
- Chapter 15 Source Code File REST API Introduction
- 一些测试相关知识
- (through page) ali time to upload the jar
- 【Verilog】HDLBits题解——Circuits/Sequential Logic/Latches and Flip-Flops
猜你喜欢
随机推荐
流式编程使用场景
self-discipline
R语言ggplot2可视化:使用patchwork包的plot_layout函数将多个可视化图像组合起来,ncol参数指定行的个数、byrow参数指定按照行顺序排布图
安防监控必备的基础知识「建议收藏」
899. 有序队列
php microtime 封装工具类,计算接口运行时间(打断点)
【Verilog】HDLBits题解——Circuits/Sequential Logic/Latches and Flip-Flops
An工具介绍之形状工具及渐变变形工具
【精品必知】Pod生命周期
Oracle安装完毕(系统盘),从系统盘转移到数据盘
五、函数的调用过程
Use %Status value
SQL分页查询_Sql根据某个字段分页
pandas连接oracle数据库并拉取表中数据到dataframe中、生成当前时间的时间戳数据、格式化为指定的格式(“%Y-%m-%d-%H-%M-%S“)并添加到csv文件名称中
Feature dimensionality reduction study notes (pca and lda) (1)
基于php网上零食商店管理系统获取(php毕业设计)
An动画优化之遮罩层动画
信创建设看广州|海泰方圆亮相2022 信创生态融合发展论坛
使用工作队列管理器(四)
Oracle is installed (system disk) and transferred from the system disk to the data disk