- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeadlockExample.java
More file actions
Latest commit
59 lines (49 loc) · 1.63 KB
/
Copy pathDeadlockExample.java
File metadata and controls
59 lines (49 loc) · 1.63 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
packagecom.codinginterview;
publicclassDeadlockExample {
publicstaticvoidmain(String[] args) throwsInterruptedException {
System.out.println("Deadlock Example");
Objectobj1 = newObject();
Objectobj2 = newObject();
Objectobj3 = newObject();
Threadt1 = newThread(newSyncthread(obj1, obj2), "t1");
Threadt2 = newThread(newSyncthread(obj2, obj3), "t2");
Threadt3 = newThread(newSyncthread(obj3, obj1), "t3");
t1.start();
Thread.sleep(5000);
t2.start();
Thread.sleep(5000);
t3.start();
}
}
classSyncthreadimplementsRunnable{
privateObjectobj1;
privateObjectobj2;
publicSyncthread(Objectobj1, Objectobj2){
this.obj1 = obj1;
this.obj2 = obj2;
}
@Override
publicvoidrun() {
Stringname = Thread.currentThread().getName();
System.out.println(name + " acquiring lock on "+ obj1);
synchronized (obj1){
System.out.println(name + " acquired lock on "+ obj1);
work();
System.out.println(name + " acquiring lock on "+ obj2);
synchronized (obj2){
System.out.println(name + " acquired lock on "+ obj2);
work();
}
System.out.println(name + " released lock on "+ obj2);
}
System.out.println(name + " releasing lock on "+ obj1);
System.out.println(name + " finished execution.");
}
privatevoidwork(){
try{
Thread.sleep(300000);
}catch (InterruptedExceptione){
e.printStackTrace();
}
}
}