📅  最后修改于: 2023-12-03 15:10:59.346000             🧑  作者: Mango
死锁是指两个或两个以上的进程在执行过程中,因争夺资源而造成一种互相等待的现象,若无外力作用,它们都将无法继续下去。
常见的死锁情况有以下几种:
当死锁出现时,常见的处理方式有以下几种:
class DeadLock implements Runnable {
private static Object lock1 = new Object();
private static Object lock2 = new Object();
private int number;
public DeadLock(int number) {
this.number = number;
}
@Override
public void run() {
if (number == 1) {
synchronized (lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (lock2) {
System.out.println("Thread 1: Holding lock 1 and 2...");
}
}
} else {
synchronized (lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (lock1) {
System.out.println("Thread 2: Holding lock 1 and 2...");
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new DeadLock(1));
Thread t2 = new Thread(new DeadLock(2));
t1.start();
t2.start();
}
}
上述代码是一个死锁的示例,其中两个线程分别占用了两个共享资源,但是它们的请求顺序不一样,导致了死锁。可以通过调整它们的请求顺序避免死锁。