-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadlock.java
More file actions
80 lines (70 loc) · 2.74 KB
/
Deadlock.java
File metadata and controls
80 lines (70 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class Deadlock {
public static void main(String[] args) {
System.out.println("Main starts");
// Two lock objects
String lock1 = "narendra";
String lock2 = "maurya";
// First thread
Thread thread1 = new Thread(() -> {
synchronized (lock1) { // Thread 1 locks lock1 first
System.out.println("Thread 1: Holding lock1...");
try { Thread.sleep(100); } catch (Exception e) {} // Simulate some work
System.out.println("Thread 1: Waiting for lock2...");
synchronized (lock2) { // Tries to lock lock2
System.out.println("Thread 1: Acquired lock2!");
}
}
});
// Second thread
Thread thread2 = new Thread(() -> {
synchronized (lock2) { // Thread 2 locks lock2 first
System.out.println("Thread 2: Holding lock2...");
try { Thread.sleep(100); } catch (Exception e) {} // Simulate some work
System.out.println("Thread 2: Waiting for lock1...");
synchronized (lock1) { // Tries to lock lock1
System.out.println("Thread 2: Acquired lock1!");
}
}
});
// Start both threads
thread1.start();
thread2.start();
}
}
/* Serialise lock acquire to avoid deadlock
public class Deadlock {
public static void main(String[] args) {
System.out.println("Main starts");
// Two lock objects
String lock1 = "narendra";
String lock2 = "maurya";
// First thread
Thread thread1 = new Thread(() -> {
// Always lock lock1 first, then lock2
synchronized (lock1) {
System.out.println("Thread 1: Holding lock1...");
try { Thread.sleep(100); } catch (Exception e) {} // Simulate some work
System.out.println("Thread 1: Waiting for lock2...");
synchronized (lock2) {
System.out.println("Thread 1: Acquired lock2!");
}
}
});
// Second thread
Thread thread2 = new Thread(() -> {
// Always lock lock1 first, then lock2
synchronized (lock1) { // Changed the order here
System.out.println("Thread 2: Holding lock1...");
try { Thread.sleep(100); } catch (Exception e) {} // Simulate some work
System.out.println("Thread 2: Waiting for lock2...");
synchronized (lock2) {
System.out.println("Thread 2: Acquired lock2!");
}
}
});
// Start both threads
thread1.start();
thread2.start();
}
}
*/