死锁(Deadlock)是指两个或多个进程在执行过程中因争夺资源而造成的一种互相等待的现象
死锁通常发生在多任务系统中,其中进程通过竞争有限的资源来完成任务
死锁通常涉及互斥、持有和等待三个条件。
public class DeadlockExample {
static class Resource {
// 用于演示的两个资源
private final Object resource1 = new Object();
private final Object resource2 = new Object();
public void method1() {
synchronized (resource1) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired resource1");
// 模拟一些操作
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource2) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired resource2");
}
}
}
public void method2() {
synchronized (resource2) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired resource2");
// 模拟一些操作
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource1) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired resource1");
}
}
}
}
public static void main(String[] args) {
final Resource resource = new Resource();
Thread thread1 = new Thread(() -> resource.method1());
Thread thread2 = new Thread(() -> resource.method2());
thread1.start();
thread2.start();
// 等待两个线程结束
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}