问:为啥以下代码会产生死锁

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:

  1. The first Thread started calls alphonse.bow(gaston), which is synchronized on the alphonse Friend object. This means the Thread must acquire the lock from this object.
  2. The second Thread started calls gaston.bow(alphonse), which is synchronized on the gastonFriend object. This means the Thread must acquire the lock from this object.
  3. The first thread started now calls bowback and waits for the lock on gaston to be released.
  4. The second thread started now calls bowback and waits for the lock on alphonse to be released.

To show the sequence of events in much more detail:

  1. main() begins to execute in the main Therad (call it Thread #1), creating two Friendinstances. So far, so good.
  2. The main Thread starts its first new Thread (call it Thread #2) with the code new Thread(new Runnable() { .... Thread #2 calls alphonse.bow(gaston), which is synchronized on the alphonse Friend object. Thread #2 thus acquires the "lock" for the alphonse object and enters the bow method.
  3. A time slice occurs here and the original Thread gets a chance to do more processing.
  4. 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 the gaston Friend object. Since no-one has yet acquired the "lock" for the gaston object instance, Thread #3 successfully acquires this lock and enters the bow method.
  5. A time slice occurs here and Thread #2 gets a chance to do more processing.
  6. Thread #2 now calls bower.bowBack(this); with bower being a reference to the instance for gaston. This is the logical equivalent of a call of gaston.bowBack(alphonse). Thus, this method is synchronized on the gaston 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 on gastonto be released. The Thread is put into a waiting state, allowing Thread #3 to execute further.
  7. Thread #3 now calls bowback, which in this instance is logically the same as the call alphonse.bowBack(gaston). To do this, it needs to acquire the lock for the alphonse 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的更多相关文章

  1. iOS学习笔记-死锁deadlock理解

    1.首先看一下官方文档的解释,这个block的队列是同步执行的,不像异步,这个方法直到block执行完毕才会返回 2.主线程一旦开启,就要先把自己的代码执行完成之后,才去执行加入到主队列中的任务 De ...

  2. [转]从Deadlock报错理解Go channel机制

    原文: https://www.jianshu.com/p/147bd63801b6 -------------------------------------- Go与其他语言不一样,它从语言层面就 ...

  3. 理解 OpenStack 高可用(HA)(1):OpenStack 高可用和灾备方案 [OpenStack HA and DR]

    本系列会分析OpenStack 的高可用性(HA)概念和解决方案: (1)OpenStack 高可用方案概述 (2)Neutron L3 Agent HA - VRRP (虚拟路由冗余协议) (3)N ...

  4. GCD的深入理解

    GCD 深入理解(一) 本文由@nixzhu翻译至raywenderlich的<grand-central-dispatch-in-depth-part-1> 虽然 GCD 已经出现过一段 ...

  5. mysql并发insert deadlock分析以及解决,无delete/update/for update

    关于并发insert操作发生deadlock这个情况,一直有很多争议,而且网上的帖子所有的例证和模拟其实不一定反映了真实的情况,例如:https://www.percona.com/blog/2012 ...

  6. GCD 深入理解:第一部分

    虽然 GCD 已经出现过一段时间了,但不是每个人都明了其主要内容.这是可以理解的:并发一直很棘手,而 GCD 是基于 C 的 API ,它们就像一组尖锐的棱角戳进 Objective-C 的平滑世界. ...

  7. 深入理解GCD(一)

    虽然 GCD 已经出现过一段时间了,但不是每个人都明了其主要内容.这是可以理解的:并发一直很棘手,而 GCD 是基于 C 的 API ,它们就像一组尖锐的棱角戳进 Objective-C 的平滑世界. ...

  8. GCD 深入理解(一)

    http://www.cocoachina.com/industry/20140428/8248.html 本文由@nixzhu翻译至raywenderlich的<grand-central-d ...

  9. 深入理解MYSQL的MDL元数据锁

    1 前言 2 MDL锁与实现 3 MDL锁的性能与并发改进 4 MDL锁的诊断 前言 好久没更新,主要是因为Inside君最近沉迷于一部动画片——<新葫芦娃兄弟>.终于抽得闲,完成了本篇关 ...

随机推荐

  1. 【小工具】根据定义的白名单字段进行Bean的拷贝

    背景 Bean的拷贝一直有一些类可以使用,比如Apache的org.apache.commons.beanutils.BeanUtils或者Spring的org.springframework.bea ...

  2. guid与Base64编码互相转换

    guid的长度比较长,本文提供一种方法,将guid转为base64字符串,只有22位长度,比较好! 参考:https://blog.csdn.net/tgghfbflishuai/article/de ...

  3. crontab 选择编辑器 select-editor

    用root第一次运行 crontab -e 会出现如题的错误,解决方法如下: 1.select-editor 选择编辑器,我选的vim.basic. 2.crontab -e 进入编辑器编辑. 推荐第 ...

  4. mongoDB用法整理

    1. mongoDB UI工具, Studio 3T,用Non_Commercial的版本就足够. 2. 查询某字段长度大于特定值的 db.test.find({ F_DAQDATA: { $type ...

  5. Windows 10 Version 1803 (Updated March 2018) MSDN 镜像下载

    微软已按先前预期于美国时间 2018 年 4 月 30 日正式向所有用户发布了 Windows 10 Version 1803 (Updated March 2018) 的 ISO 镜像下载,按微软官 ...

  6. Vue:$set和$delete

    一.$set 在开始讲解$set之前先看下面的一段代码,实现的功能:当点击“添加”按钮时,动态的给data里面的对象添加属性和值,代码示例如下: <!DOCTYPE html> <h ...

  7. 第四百一十六节,Tensorflow简介与安装

    第四百一十六节,Tensorflow简介与安装 TensorFlow是什么 Tensorflow是一个Google开发的第二代机器学习系统,克服了第一代系统DistBelief仅能开发神经网络算法.难 ...

  8. 加入ffmpeg播放视屏

    下面的字反了..,另外没声音 2018-4-28 前段时间已经做的差不多了,音频的pack取出来用openAL播放,并实现了视屏同步播放,并且支持unity 现在的问题就是支持大分辨率视屏播放的问题, ...

  9. 寄存器理解 及 X86汇编入门

    本文整理自多材料源,感谢原址分享,请查看末尾Url I, 汇编语言分类: 汇编语言和CPU息息相关,但是不能把汇编语言完全等同于CPU的机器指令.不同架构的CPU指令并不相同,如x86,powerpc ...

  10. 目前(2018年)在北京java程序员平均薪水是多少呢?

    1. 这个要看看个人java开发能力,你那个自己带项目做团队的比较高哦 2. 一般来说刚毕业的本科实习生大约在5000左右,干半年基本都张到7.5左右了. 3. Java程序员一般都集中在北京,上海和 ...