Sunday, April 6, 2025

Deadlock

 class DeadlockExample {

public static void main(String[] args) {
final Object lock1 = new Object();
final Object lock2 = new Object();

Thread t1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1 locked lock1");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (lock2) {
System.out.println("Thread 1 locked lock2");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2 locked lock2");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (lock1) {
System.out.println("Thread 2 locked lock1");
}
}
});
t1.start();
t2.start();
}
}

No comments:

Post a Comment

Static vs Non Static Inner class

Understanding Static vs Non-Static Inner Classes in Java The Hidden Reference That Most Java Developers Never See One of the most misunderst...