-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
64 lines (56 loc) · 1.11 KB
/
Copy pathMain.java
File metadata and controls
64 lines (56 loc) · 1.11 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
package dreadLock;
class SharedObject{
final Object lockA = new Object();
final Object lockB = new Object();
int accountA = 1000;
int accountB = 2000;
public void a2b (int balance){
synchronized (lockA){
accountA -= balance;
synchronized (lockB){
accountB += balance;
}
}
}
public void b2a (int balance){
synchronized (lockB){
accountA -= balance;
synchronized (lockA){
accountB += balance;
}
}
}
}
class Athread extends Thread{
public void run(){
for (int i = 0; i <Main.LOOP; i++){
Main.shared.a2b(1);
if (i % 100 == 0){
System.out.println(".");
}
}
}
}
class Bthread extends Thread{
public void run(){
for (int i = 0; i <Main.LOOP; i++){
Main.shared.b2a(1);
if (i % 100 == 0){
System.out.println(".");
}
}
}
}
public class Main {
final static int LOOP = 10000;
public static SharedObject shared = new SharedObject();
public static void main(String[] args) throws Exception {
Thread t1 = new Athread();
Thread t2 = new Bthread();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("END");
}
}