当前位置:网站首页>Interview Question: Implementing Deadlocks
Interview Question: Implementing Deadlocks
2022-07-31 23:32:00 【Jade-faced Jiaolong】
The idea of implementing deadlock is very simple:
1. First, there must be two resources 1 and 2, and two threads A and B.
2. Thread A grabs resource 1, and thread B grabs resource 2.
3. At the same time, if thread A wants resource 2, he has to wait for thread B to give up resource 2 in his hand; if thread B wants resource 1, he has to wait for thread A to give up resource 1 in his hand.locked.
public class Main {public static void main(String[] args) {//two resourcesObject a = new Object();Object b = new Object();// a threadnew Thread(() -> {//go to get a firstsynchronized (a){System.out.println(Thread.currentThread().getName() + ": i got a!");//Sleep for two seconds to ensure that another thread can grab another resourcetry {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}// go to get bsynchronized(b){System.out.println(Thread.currentThread().getName() + ": i got b!");}}}).start();// another threadnew Thread(()->{//go to get b firstsynchronized(b){System.out.println(Thread.currentThread().getName() + ": i got b!");try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}// go to get asynchronized (a){System.out.println(Thread.currentThread().getName() + ": i got a!");}}}).start();}}
边栏推荐
猜你喜欢
Audio alignment using cross-correlation
数据分析(一)——matplotlib
消息队列消息存储设计(架构实战营 模块八作业)
SVN server construction + SVN client + TeamCity integrated environment construction + VS2019 development
【Acwing】The 62nd Weekly Game Solution
嵌入式开发没有激情了,正常吗?
Binary tree non-recursive traversal
Document management and tools in the development process
如何减少软件设计和实现之间鸿沟
基于mysql的消息队列设计
随机推荐
Shell common scripts: Nexus batch upload local warehouse enhanced version script (strongly recommended)
Unity - LineRenderer show a line
面试突击69:TCP 可靠吗?为什么?
#yyds干货盘点# 面试必刷TOP101:链表中环的入口结点
博弈论(Depu)与孙子兵法(42/100)
"SDOI2016" Journey Problem Solution
逐步手撕轮播图3(保姆级教程)
leetcode:126. 单词接龙 II
IPD process terminology
SVN服务器搭建+SVN客户端+TeamCity集成环境搭建+VS2019开发
Binary tree non-recursive traversal
@JsonFormat(pattern="yyyy-MM-dd") time difference problem
面试突击69:TCP 可靠吗?为什么?
mysql having的用法
[Reading Notes -> Data Analysis] 02 Data Analysis Preparation
数据分析(一)——matplotlib
【Acwing】第62场周赛 题解
基于mysql的消息队列设计
Handwritten a simple web server (B/S architecture)
/etc/sysconfig/network-scripts configure the network card