https://wx.kaifamiao.info/index.php/2023/11/28/java-zhong-ru-he-xie-yi-duan-jian-dan-de-si-suo-da/
死锁是多线程编程中的一种常见问题,它发生在两个或多个线程相互等待对方释放锁的情况下。下面是一个简单的Java代码示例,演示了如何创建一个死锁:
public class DeadlockExample {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Task1());
Thread thread2 = new Thread(new Task2());
thread1.start();
thread2.start();
}
private static class Task1 implements Runnable{
@Override
public void run() {
synchronized (lock1) {
System.out.println("Task1 acquired lock1");
// Adding some delay to increase the likelihood of deadlock
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (lock2) {
System.out.println("Task1 acquired lock2");
}
}
}
}
private static class Task2 implements Runnable{
@Override
public void run() {
synchronized (lock2) {
System.out.println("Task1 acquired lock2");
// Adding some delay to increase the likelihood of deadlock
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (lock1) {
System.out.println("Task1 acquired lock1");
}
}
}
}
}
在这个例子中,两个线程(Task1和Task2)分别尝试获取两个不同的锁(lock1和lock2),但是它们获取锁的顺序是相反的。这种情况可能导致死锁,因为一个线程持有lock1并等待lock2,而另一个线程持有lock2并等待lock1。如果你运行这个程序,有可能会观察到死锁的发生。注意,死锁的发生是不确定的,它取决于线程的调度和执行顺序。