当前位置:网站首页>面试题:实现死锁
面试题:实现死锁
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();
}
}
边栏推荐
猜你喜欢
【Acwing】第62场周赛 题解
Flink 1.13(八)CDC
Judging decimal points and rounding of decimal operations in Golang
Unity-LineRenderer显示一条线
Golang - from entry to abandonment
20. Support vector machine - knowledge of mathematical principles
消息队列存储消息数据的MySQL表格
IJCAI2022 | 代数和逻辑约束的混合概率推理
基于simulink的Passive anti-islanding-UVP/OVP and UFP/OFP被动反孤岛模型仿真
How to debug TestCafe
随机推荐
"SDOI2016" Journey Problem Solution
Write a database document management tool based on WPF repeating the wheel (1)
21. Support Vector Machine - Introduction to Kernel Functions
TypeScript 的组件
标段参数说明
Program processes and threads (concurrency and parallelism of threads) and basic creation and use of threads
Network security - crack WiFi through handshake packets (detailed tutorial)
SQL注入 Less42(POST型堆叠注入)
A high-quality WordPress download site template theme developed abroad
Dry goods | 10 tips for MySQL add, delete, change query performance optimization
高等代数_证明_任何矩阵都相似于一个上三角矩阵
日常--Kali开启SSH(详细教程)
The latest masterpiece!Alibaba just released the interview reference guide (Taishan version), I just brushed it for 29 days
@JsonFormat(pattern=“yyyy-MM-dd“)时间差问题
Collation of knowledge points in Ningbo University NBU IT project management final exam
如何减少软件设计和实现之间鸿沟
Unity-通过预制件和克隆方法动态实现各个UGUI下控件的创建和显示
uniapp小程序检查、提示更新
Flutter教程之 01配置环境并运行demo程序 (教程含源码)
HTC using official firmware as bottom bag made ROM brush card bag tutorial