概念:所谓死锁是指两个或两个以上的进程在执行过程中,因争夺同一资源而造成的一种互相等待的现象,若无外力作用,它们都将无法进行下去,此时称系统处于死锁状态或系统产生了死锁,
class K extends Thread{
private Integer p1 = null;
private Integer p2 = null;
private String name;
public K(Integer p1, Integer p2, String name){
this.p1 = p1;
this.p2 = p2;
this.name = name;
}
public void run(){
//第一个线程先锁p1,再锁p2
try {
if("张三".equals(this.name)) {
synchronized (p1) {
Thread.sleep(1);
synchronized (p2) {
}
}
}else {//第二个线程先锁p2,再在锁p1
synchronized (p2){
Thread.sleep(1);
synchronized (p1){
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class 死锁 {
public static void main(String[] args) {
Integer p1 = 23;
Integer p2 = 45;
K n1 = new K(p1,p2,"张三");
K n2 = new K(p1,p2,"陈二");
n1.start();
n2.start();
}
}
当交叉访问对方资源的时候会出现死锁
解决方法:避免交叉访问对方资源,按同一顺序访问,就不会出现死锁问题。