当前位置:网站首页>Multithreading deadlock and synchronized
Multithreading deadlock and synchronized
2022-07-25 10:16:00 【Look at the bugs】
Deadlock
Four necessary conditions for deadlock generation ( Just avoid one of them )
1, mutual exclusion : A group member can only be used by one process at a time
2, Request to keep the condition : When a process is blocked by requesting resources, the resources it has obtained remain
3, Conditions of non deprivation : Process to get resources , Before use , Can't be forcibly deprived
4, Circulation and other conditions : Several processes form a head to tail cycle waiting for resources
package TestSynchronized;
public class DeadLock {
public static void main(String[] args) {
Makeup g1=new Makeup(0," Grey Gu Liang ");
Makeup g2=new Makeup(1," Snow White ");
g1.start();
g2.start();
}
}
// Lipstick
class Lipstick{
}
// Mirror
class Mirror{
}
class Makeup extends Thread{
// Only one resource is needed , use static To make sure there's only one
static Lipstick lipstick=new Lipstick();
static Mirror mirror=new Mirror();
int choose;
String girlName; // People who use cosmetics
Makeup(int choose,String girlName){
this.choose=choose;
this.girlName=girlName;
}
@Override
public void run() {
try {
Makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Make up , Hold each other's locks , You need to get the other person's resources
private void Makeup() throws InterruptedException {
if(choose==0){
synchronized (lipstick) {
// Get the lipstick lock
System.out.println(this.girlName+" Get the lipstick lock ");
Thread.sleep(1000);
}
synchronized (mirror){
System.out.println(this.girlName+" A second later, you get the lock of the mirror ");
}
}else {
synchronized (mirror) {
// Get the lock of the mirror
System.out.println(this.girlName+" Get the lock of the mirror ");
Thread.sleep(2000);
}
synchronized (lipstick){
System.out.println(this.girlName+" Two seconds later, you get the lock of lipstick ");
}
}
}
}
synchronized
synchronized(obj) It's called a synchronization monitor
The object that needs to be locked is the object that needs to be added, deleted or modified
The execution of the lock
1, First thread , Lock synchronization monitor , Execute the code
2, The second thread , Found sync monitor locked , cannot access
3, Third thread , Thread access completed , Unlock sync monitor
4, Fourth thread , It is found that the synchronization monitor is not locked , Let that lock and access
Problems caused by locks :
1, A thread holding a lock will cause all other threads that need the lock to hang
2, In the competition of multithreading , Lock , Releasing lock will lead to more context switching and scheduling delay , Cause performance problems
3, If a high priority thread waits for a low priority thread to release the lock , Will result in priority , Cause performance problems
If there are multiple objects to lock, the solution :
You can put multiple objects into one class , Then lock this class
package TestSynchronized;
// It's not safe to buy tickets
// There will be negative numbers
// Add one more syncronized
public class testTickets implements Runnable{
public static void main(String[] args) {
// TODO Auto-generated method stub
testTickets testTickets =new testTickets();
Thread thread =new Thread(testTickets," Xiaohong ");
Thread thread2 =new Thread(testTickets," liu ");
Thread thread3 =new Thread(testTickets," Small blue ");
thread.start();
thread2.start();
thread3.start();
}
class buyTickets implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
}
}
private int ticketNumbers=10;
private boolean flag =true; // External stop mode
@Override
public void run() {
// TODO Auto-generated method stub
// Buy tickets
while (flag) {
buy();
// Analog delay
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//synchronized Synchronization method , When locked this
// The object of a lock is the amount of change Additions and deletions
private synchronized void buy(){
// Judge whether there is a ticket
if (ticketNumbers<=0) {
flag=false;
return ;
}
// Buy tickets
System.out.println(Thread.currentThread().getName()+" Get "+ticketNumbers--);
}
}
// Lock lock
Usage method : Usually put the lock on try finally In the method
1,Lock It's a display lock ( Manually open and close the lock )Synchrocized It's an implicit lock , Out of scope auto release
2,Lock Only code locks ,Synchrocized There are code block locks and method locks
Priority of use :Lock> Synchronization code block ( It has entered the method body , Allocated the corresponding resources )> Synchronization method ( Outside the method body )
package TestSynchronized;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestTicket testLock=new TestTicket();
new Thread(testLock).start();
new Thread(testLock).start();
new Thread(testLock).start();
}
}
class TestTicket implements Runnable{
int ticketNums=10;
// Definition Lock lock
private final ReentrantLock lock=new ReentrantLock(); // Definition lock lock
@Override
public void run() {
while(true){
try{
lock.lock(); // Lock
if(ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else{
break;
}
}finally {
// Usually put the lock on try finally In the method
// Unlock
lock.unlock();
}
}
}
}
边栏推荐
- Duplicate SSL_ Anti spoofing, spoofing attacks and deep forgery detection using wav2vec 2.0 and data enhanced automatic speaker authentication
- Configuring ROS development environment with vscode: Causes and solutions to the problem of ineffective code modification
- Chrome开发者工具详解
- The first week of the fifth stage
- 线程池的设计和原理
- JS uses requestanimationframe to detect the FPS frame rate of the current animation in real time
- 用户喜好
- JSONObject解析json格式的终极总结
- 复现 SSL_Anti-spoofing, 使用 wav2vec 2.0 和数据增强的自动说话人认证的欺骗攻击与深度伪造检测
- Subtotal of rospy odometry sinkhole
猜你喜欢

JS uses requestanimationframe to detect the FPS frame rate of the current animation in real time

Copy the old project into a web project

将 conda 虚拟环境 env 加入 jupyter kernel

线程池的设计和原理

字典树的使用

JDBC总结

升级 GLIBC 2.29 checking LD_LIBRARY_PATH variable... contains current directory error 解决方案

IDEA整体字体大小修改

OSPF协议的配置(以华为eNSP为例)

【专栏】RPC系列(理论)-夜的第一章
随机推荐
emmet语法速查 syntax基本语法部分
OSPF协议的配置(以华为eNSP为例)
MVC three-tier architecture understanding
21. Merge Two Sorted Lists
Filter过滤器详解(监听器以及它们的应用)
四舍五入取近似值
Salt FAQs
The first week of the fifth stage
Swing组件
VSCode Latex Workshop 设置 XeLatex 编译
UE4源码的获取和编译
字符串最长公共前缀
Loam transformtoend function integrating IMU details
Ubuntu20.04系统下安装MySQL数据库5.7.29版本
Subtotal of rospy odometry sinkhole
简易加法计算器
修改mysql的分组报错Expression #1 of SELECT list is not in GROUP
GUI窗口
力扣刷题组合问题总结(回溯)
Pytorch 张量列表转换为张量 List of Tensor to Tensor 使用 torch.stack()