目录
死锁是什么
死锁是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象
死锁产生的主要原因
1.系统资源不足
2.进程运行推进的顺序不合适
3.资源分配不当
扫描二维码关注公众号,回复:
10325356 查看本文章
![](/qrcode.jpg)
死锁的java代码模拟
DeadLock类
package test2;
import java.util.concurrent.TimeUnit;
public class DeadLock implements Runnable{
private String firstlock;
private String secondlock;
public DeadLock(String firstlock, String secondlock) {
this.firstlock = firstlock;
this.secondlock = secondlock;
}
@Override
public void run() {
synchronized (firstlock){
System.out.println(Thread.currentThread().getName()+"\t持有" + firstlock + "需要" + secondlock);
try {
TimeUnit.SECONDS.sleep(2L);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (secondlock){
System.out.println(Thread.currentThread().getName()+"\t持有" + secondlock + "需要" + firstlock);
}
}
}
}
测试类
package test2;
public class Main {
public static void main(String[] args){
String lockA = "A";
String lockB = "B";
new Thread(new DeadLock(lockA,lockB),"线程A").start();
new Thread(new DeadLock(lockB,lockA),"线程B").start();
}
}