理解Deadlock
问:为啥以下代码会产生死锁
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s has bowed back to me!%n",
this.name, bower.getName());
}
} public static void main(String[] args) {
final Friend alphonse = new Friend("Alphonse");
final Friend gaston = new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
答:
In Java, each Object
provides the ability for a Thread to synchronize
, or lock, on it. When a method is synchronized, the method uses its object instance as the lock. In your example, the methods bow
and bowBack
are both synchronized
, and both are in the same class Friend
. This means that any Thread executing these methods will synchronize on a Friend
instance as its lock.
A sequence of events which will cause a deadlock is:
- The first Thread started calls
alphonse.bow(gaston)
, which issynchronized
on thealphonse
Friend
object. This means the Thread must acquire the lock from this object. - The second Thread started calls
gaston.bow(alphonse)
, which issynchronized
on thegaston
Friend
object. This means the Thread must acquire the lock from this object. - The first thread started now calls
bowback
and waits for the lock ongaston
to be released. - The second thread started now calls
bowback
and waits for the lock onalphonse
to be released.
To show the sequence of events in much more detail:
main()
begins to execute in the main Therad (call it Thread #1), creating twoFriend
instances. So far, so good.- The main Thread starts its first new Thread (call it Thread #2) with the code
new Thread(new Runnable() { ...
. Thread #2 callsalphonse.bow(gaston)
, which issynchronized
on thealphonse
Friend
object. Thread #2 thus acquires the "lock" for thealphonse
object and enters thebow
method. - A time slice occurs here and the original Thread gets a chance to do more processing.
- The main Thread starts a second new Thread (call it Thread #3), just like the first one. Thread #3 calls
gaston.bow(alphonse)
, which is synchronized on thegaston
Friend
object. Since no-one has yet acquired the "lock" for thegaston
object instance, Thread #3 successfully acquires this lock and enters thebow
method. - A time slice occurs here and Thread #2 gets a chance to do more processing.
- Thread #2 now calls
bower.bowBack(this);
withbower
being a reference to the instance forgaston
. This is the logical equivalent of a call ofgaston.bowBack(alphonse)
. Thus, this method issynchronized
on thegaston
instance. The lock for this object has already been acquired and is held by another Thread (Thread #3). Thus, Thread #2 has to wait for the lock ongaston
to be released. The Thread is put into a waiting state, allowing Thread #3 to execute further. - Thread #3 now calls
bowback
, which in this instance is logically the same as the callalphonse.bowBack(gaston)
. To do this, it needs to acquire the lock for thealphonse
instance, but this lock is held by Thread #2. This Thread is now put into a waiting state.
And you are now in a position where neither Thread can execute. Both Thread #2 and Thread #3 are waiting for a lock to be released. But neither lock can be released without a Thread making progress. But neither thread can make progress without a lock being released.
Thus: Deadlock!
Deadlocks very often depend on a specific sequence of events occurring, which can make then difficult to debug since they can be difficult to reproduce.
原文链接:https://stackoverflow.com/questions/749641/how-does-synchronized-work-in-java
理解Deadlock的更多相关文章
- iOS学习笔记-死锁deadlock理解
1.首先看一下官方文档的解释,这个block的队列是同步执行的,不像异步,这个方法直到block执行完毕才会返回 2.主线程一旦开启,就要先把自己的代码执行完成之后,才去执行加入到主队列中的任务 De ...
- [转]从Deadlock报错理解Go channel机制
原文: https://www.jianshu.com/p/147bd63801b6 -------------------------------------- Go与其他语言不一样,它从语言层面就 ...
- 理解 OpenStack 高可用(HA)(1):OpenStack 高可用和灾备方案 [OpenStack HA and DR]
本系列会分析OpenStack 的高可用性(HA)概念和解决方案: (1)OpenStack 高可用方案概述 (2)Neutron L3 Agent HA - VRRP (虚拟路由冗余协议) (3)N ...
- GCD的深入理解
GCD 深入理解(一) 本文由@nixzhu翻译至raywenderlich的<grand-central-dispatch-in-depth-part-1> 虽然 GCD 已经出现过一段 ...
- mysql并发insert deadlock分析以及解决,无delete/update/for update
关于并发insert操作发生deadlock这个情况,一直有很多争议,而且网上的帖子所有的例证和模拟其实不一定反映了真实的情况,例如:https://www.percona.com/blog/2012 ...
- GCD 深入理解:第一部分
虽然 GCD 已经出现过一段时间了,但不是每个人都明了其主要内容.这是可以理解的:并发一直很棘手,而 GCD 是基于 C 的 API ,它们就像一组尖锐的棱角戳进 Objective-C 的平滑世界. ...
- 深入理解GCD(一)
虽然 GCD 已经出现过一段时间了,但不是每个人都明了其主要内容.这是可以理解的:并发一直很棘手,而 GCD 是基于 C 的 API ,它们就像一组尖锐的棱角戳进 Objective-C 的平滑世界. ...
- GCD 深入理解(一)
http://www.cocoachina.com/industry/20140428/8248.html 本文由@nixzhu翻译至raywenderlich的<grand-central-d ...
- 深入理解MYSQL的MDL元数据锁
1 前言 2 MDL锁与实现 3 MDL锁的性能与并发改进 4 MDL锁的诊断 前言 好久没更新,主要是因为Inside君最近沉迷于一部动画片——<新葫芦娃兄弟>.终于抽得闲,完成了本篇关 ...
随机推荐
- 【转】使用minizip解压缩多个文件(基于zlib)
原帖子:使用minizip解压缩多个文件(基于zlib) 写作目的:之前在网上看到很多人在寻找可以解压缩多个文件的程序,其中有尝试zlib的,使用zlib的源码可以生成后缀为点gz的压缩文件,但是一次 ...
- Gitee vs插件(Gitee Extension for Visual Studio)
Gitee 码云(gitee.com)是开源中国推出的代码托管平台,支持 Git 和 SVN,提供免费的私有仓库托管. https://gitee.com/GitGroup/Gitee.VisualS ...
- Git入门到高级系列2-git高级操作
视频课程地址 腾讯课堂 git 清理 git clean命令用来从你的工作目录中删除所有没有tracked过的文件. 命令 说明 git clean -n 告诉你哪些文件会被删除. 记住他不会真正的删 ...
- C语言 · 勾股数
勾股数 勾股定理,西方称为毕达哥拉斯定理,它所对应的三角形现在称为:直角三角形. 已知直角三角形的斜边是某个整数,并且要求另外两条边也必须是整数. 求满足这个条件的不同直角三角形的个数. [数据格式] ...
- halcon之NCC匹配
NCC匹配 基于Normalized cross correlation(NCC)用来比较两幅图像的相似程度已经是一个常见的图像处理手段.在工业生产环节检测.监控领域对对象检测与识别均有应用.NCC算 ...
- MyBatis总结五:#{}和${}的用法和区别
From: https://www.cnblogs.com/blazeZzz/p/9295634.html #{}的用法: 我们发现,在Mapper.xml映射文件中,经常使用#{属性名} 来作为SQ ...
- 81For全栈技术网
你想了解前端吗? 你想了解后端吗? 你想了解设计吗? 81For全栈技术这里包含了互联网所有内容,81For.com是全栈技术网,包括:前端.后端.全栈.jquery.vue.react.router ...
- linux系统搜索文件中关键字的位置
grep -Irn “ubuntu”-------即查出文件的目录路径
- Microsoft office 2019 正式版镜像下载
http://www.xitongtiandi.net/soft_yy/4373.htmlMicrosoft office 2019 正式版镜像下载 http://www.xitongtiandi.n ...
- xcode8 iOS函数返回值使用警告
没有使用返回值时, 警告 swift: @warn_unused_result func doSomething() -> Bool { return true } OC: - (BOOL)do ...