-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadLockTest.java
More file actions
83 lines (70 loc) · 1.7 KB
/
DeadLockTest.java
File metadata and controls
83 lines (70 loc) · 1.7 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
81
82
83
package test;
/**
* DeadLockTest
*
* @author Eugene Matyushkin
* @version 1.0
*/
public class DeadLockTest
{
public static void main(String[] args)
{
A a1 = new A();
A a2 = new A();
Thread t1 = new Thread(new Tester(a1, a2));
Thread t2 = new Thread(new Tester(a2, a1));
t1.start();
t2.start();
}
public static class Tester implements Runnable
{
static int nextId = 1;
private A obj1;
private A obj2;
private int id = 0;
public Tester(A obj1, A obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
id = nextId++;
}
public void run()
{
print("Setting value to obj1... ");
obj1.setValue(id);
print("done.");
print("value of obj1: " + obj1.getValue());
print("Comparing objects... ");
print("Done. Result: " + ((obj1.equals(obj2)) ? "equal" : "not equal"));
}
private void print(String msg)
{
System.out.println("Thread #" + id + ": " + msg);
}
}
public static class A
{
private int value = 0;
synchronized void setValue(int value)
{
this.value = value;
}
synchronized int getValue()
{
return value;
}
public synchronized boolean equals(Object o)
{
A a = (A) o;
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.err.println("Interrupted!");
}
return value == a.getValue();
}
}
}