下面是一个简单的Java死锁的示例代码:
public class DeadlockDemo {
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1 acquired lock 1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Thread 1 acquired lock 2");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2 acquired lock 2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2 acquired lock 1");
}
}
});
t1.start();
t2.start();
}
}
在这个示例中,有两个线程t1和t2,它们都试图获取两个锁lock1和lock2,但是获取锁的顺序不同。如果t1先获取了lock1,然后尝试获取lock2,同时t2先获取了lock2,然后尝试获取lock1,就会发生死锁。
在这种情况下,t1持有lock1,等待t2释放lock2,而t2持有lock2,等待t1释放lock1,两个线程互相等待对方释放锁,形成死锁。