Middle — Middle+
Create a code example that leads to deadlock without the possibility of release.
sobes.tech AI
Answer from AI
Below is a Java code example demonstrating a deadlock between two threads that attempt to acquire two monitor objects in different orders:
public class DeadlockExample {
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
System.out.println("Thread 1 acquired lock1");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (lock2) {
System.out.println("Thread 1 acquired lock2");
}
}
}
public void method2() {
synchronized (lock2) {
System.out.println("Thread 2 acquired lock2");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (lock1) {
System.out.println("Thread 2 acquired lock1");
}
}
}
public static void main(String[] args) {
DeadlockExample example = new DeadlockExample();
Thread t1 = new Thread(example::method1);
Thread t2 = new Thread(example::method2);
t1.start();
t2.start();
}
}
In this example:
- Thread 1 acquires
lock1, then tries to acquirelock2. - Thread 2 acquires
lock2, then tries to acquirelock1.
If both threads manage to acquire their first lock before the second thread acquires the second lock, a deadlock occurs — each thread waits for the resource held by the other, causing the program to hang.