JAVA 100道题(25)

时间:2024-04-03 07:34:00
public class DeadlockExample {
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired lock1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + Thread.currentThread().getId() + " is waiting for lock2");
synchronized (lock2) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired lock2");
}
}
}
public void method2() {
synchronized (lock2) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired lock2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + Thread.currentThread().getId() + " is waiting for lock1");
synchronized (lock1) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired lock1");
}
}
}
public static void main(String[] args) {
DeadlockExample deadlockExample = new DeadlockExample();
Thread thread1 = new Thread(() -> deadlockExample.method1());
Thread thread2 = new Thread(() -> deadlockExample.method2());
thread1.start();
thread2.start();
}
}