-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadDeadlock.java
66 lines (53 loc) · 1.48 KB
/
ThreadDeadlock.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
56
57
58
59
60
61
62
63
64
65
66
package concept.examples.threads;
class Resource {
}
class SomeOperation {
Resource resource1 = new Resource();
Resource resource2 = new Resource();
void method1() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + "is in method1");
synchronized (resource1) {
System.out.println(Thread.currentThread().getName()
+ "is going to sleep");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()
+ "is out of sleep and will wait for resource 2");
synchronized (resource2) {
// SOME CODE GOES IN HERE
}
}
}
void method2() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + "is in method2");
synchronized (resource2) {
System.out.println(Thread.currentThread().getName()
+ "is going to sleep");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()
+ "is out of sleep and will wait for resource 1");
synchronized (resource1) {
// SOME CODE GOES IN HERE
}
}
}
}
public class ThreadDeadlock implements Runnable {
SomeOperation operation = new SomeOperation();
@Override
public void run() {
try {
operation.method1();
operation.method2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ThreadDeadlock r = new ThreadDeadlock();
Thread one = new Thread(r);
Thread two = new Thread(r);
one.start();
two.start();
}
}