forked from thisisshub/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Deadlock.java
55 lines (53 loc) · 1.77 KB
/
Deadlock.java
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
public class DeadLockProgram {
// Creating Object Locks
static Object ObjectLock1 = new Object();
static Object ObjectLock2 = new Object();
private static class ThreadName1 extends Thread {
public void run() {
synchronized (ObjectLock1) {
System.out.println("Thread 1: Has ObjectLock1");
/* Adding sleep() method so that
Thread 2 can lock ObjectLock2 */
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Waiting for ObjectLock 2");
/*Thread 1 has ObjectLock1
but waiting for ObjectLock2*/
synchronized (ObjectLock2) {
System.out.println("Thread 1: No DeadLock");
}
}
}
}
private static class ThreadName2 extends Thread {
public void run() {
synchronized (ObjectLock2) {
System.out.println("Thread 2: Has ObjectLock2");
/* Adding sleep() method so that
Thread 1 can lock ObjectLock1 */
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Waiting for ObjectLock 1");
/*Thread 2 has ObjectLock2
but waiting for ObjectLock1*/
synchronized (ObjectLock1) {
System.out.println("Thread 2: No DeadLock");
}
}
}
}
public static void main(String args[]) {
ThreadName1 thread1 = new ThreadName1();
ThreadName2 thread2 = new ThreadName2();
thread1.start();
thread2.start();
}
}