当前位置:网站首页>面试题:实现死锁
面试题:实现死锁
2022-07-31 22:56:00 【玉面大蛟龙】
实现死锁的思路很简单:
1、首先要有两个资源1和2,有两个线程A和B。
2、线程A抢到了资源1,线程B抢到了资源2。
3、同时,线程A想要资源2,他要等待线程B放弃手里的资源2;线程B想要资源1,他要等待线程A放弃手里的资源1,这个时候就形成死锁了。
public class Main {
public static void main(String[] args) {
//两个资源
Object a = new Object();
Object b = new Object();
//一个线程
new Thread(() -> {
//先去拿a
synchronized (a){
System.out.println(Thread.currentThread().getName() + ": i got a!");
//睡两秒,保证另一个线程能抢到另一个资源
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//再去拿b
synchronized (b){
System.out.println(Thread.currentThread().getName() + ": i got b!");
}
}
}).start();
//另一个线程
new Thread(()->{
//先去拿b
synchronized (b){
System.out.println(Thread.currentThread().getName() + ": i got b!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//再去拿a
synchronized (a){
System.out.println(Thread.currentThread().getName() + ": i got a!");
}
}
}).start();
}
}
边栏推荐
- SQL injection Less38 (stack injection)
- MySQL数据库‘反斜杠\’ ,‘单引号‘’,‘双引号“’,‘null’无法存储
- Go mode tidy reports an error go warning “all” matched no packages
- 如何导入 Golang 外部包并使用它?
- Flink 1.13(八)CDC
- C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处
- 嵌入式开发没有激情了,正常吗?
- [Code Hoof Set Novice Village 600 Questions] Leading to the combination of formulas and programs
- Advanced Algebra _ Proof _ Any matrix is similar to an upper triangular matrix
- MLP神经网络,GRNN神经网络,SVM神经网络以及深度学习神经网络对比识别人体健康非健康数据
猜你喜欢
C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处
Audio alignment using cross-correlation
支付模块实现
leetcode:126. 单词接龙 II
基于mysql的消息队列设计
Flink_CDC construction and simple use
Binary tree non-recursive traversal
I don't know what to do with sync issues
VOT2021 game introduction
The latest masterpiece!Alibaba just released the interview reference guide (Taishan version), I just brushed it for 29 days
随机推荐
Advanced Algebra _ Proof _ Any matrix is similar to an upper triangular matrix
"SDOI2016" Journey Problem Solution
「APIO2010」巡逻 题解
支付模块实现
Recognize anomalies (you will understand after reading this)
Program processes and threads (concurrency and parallelism of threads) and basic creation and use of threads
How to identify fake reptiles?
基于simulink的Passive anti-islanding-UVP/OVP and UFP/OFP被动反孤岛模型仿真
手写一个简单的web服务器(B/S架构)
The uniapp applet checks and prompts for updates
【ACM】2022.7.31训练赛
The difference between adding or not adding the ref keyword when a variable of reference type is used as a parameter in a method call in C#
高等代数_证明_任何矩阵都相似于一个上三角矩阵
Several methods of mysql backup table
程序进程和线程(线程的并发与并行)以及线程的基本创建和使用
I don't know what to do with sync issues
C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处
A high-quality WordPress download site template theme developed abroad
内核对设备树的处理
GateWay implements load balancing