面試官:手寫一個(gè)必然死鎖的例子
閱讀本文大概需要 5 分鐘。
來自:blog.csdn.net/xiewenfeng520/article/details/107230996
前言
什么是死鎖? 死鎖有什么危害和特點(diǎn)? 代碼實(shí)現(xiàn)一個(gè)必然死鎖的示例 分析死鎖的過程
推薦下自己做的 Spring Boot 的實(shí)戰(zhàn)項(xiàng)目: https://github.com/YunaiV/ruoyi-vue-pro
項(xiàng)目環(huán)境
jdk 1.8
github 地址:https://github.com/huajiexiewenfeng/java-concurrent
本章模塊:deadlock
推薦下自己做的 Spring Cloud 的實(shí)戰(zhàn)項(xiàng)目: https://github.com/YunaiV/onemall
1.什么是死鎖?
關(guān)鍵詞:并發(fā)場景,多線程
關(guān)鍵詞:互不相讓

2.死鎖的影響和危害
2.1 死鎖的影響
2.1.1 數(shù)據(jù)庫中
2.1.2 JVM 中
2.2 死鎖的危害以及特點(diǎn)
關(guān)鍵詞:概率性事件
關(guān)鍵詞:危害大,發(fā)生幾率不高
3.必然死鎖示例
public?class?MustDeadLockDemo?{
????public?static?void?main(String[]?args)?{
????????Object?lock1?=?new?Object();
????????Object?lock2?=?new?Object();
????????new?Thread(new?DeadLockTask(lock1,?lock2,?true),?"線程1").start();
????????new?Thread(new?DeadLockTask(lock1,?lock2,?false),?"線程2").start();
????}
????static?class?DeadLockTask?implements?Runnable?{
????????private?boolean?flag;
????????private?Object?lock1;
????????private?Object?lock2;
????????public?DeadLockTask(Object?lock1,?Object?lock2,?boolean?flag)?{
????????????this.lock1?=?lock1;
????????????this.lock2?=?lock2;
????????????this.flag?=?flag;
????????}
????????@Override
????????public?void?run()?{
????????????if?(flag)?{
????????????????synchronized?(lock1)?{
????????????????????System.out.println(Thread.currentThread().getName()?+?"->拿到鎖1");
????????????????????try?{
????????????????????????Thread.sleep(1000);
????????????????????}?catch?(InterruptedException?e)?{
????????????????????????e.printStackTrace();
????????????????????}
????????????????????System.out.println(Thread.currentThread().getName()?+?"->等待鎖2釋放...");
????????????????????synchronized?(lock2)?{
????????????????????????System.out.println(Thread.currentThread().getName()?+?"->拿到鎖2");
????????????????????}
????????????????}
????????????}
????????????if?(!flag)?{
????????????????synchronized?(lock2)?{
????????????????????System.out.println(Thread.currentThread().getName()?+?"->拿到鎖2");
????????????????????try?{
????????????????????????Thread.sleep(1000);
????????????????????}?catch?(InterruptedException?e)?{
????????????????????????e.printStackTrace();
????????????????????}
????????????????????System.out.println(Thread.currentThread().getName()?+?"->等待鎖1釋放...");
????????????????????synchronized?(lock1)?{
????????????????????????System.out.println(Thread.currentThread().getName()?+?"->拿到鎖1");
????????????????????}
????????????????}
????????????}
????????}
????}
}

4.過程分析




