|
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(); |
|
} |
|
} |