-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunner.java
More file actions
75 lines (62 loc) · 1.66 KB
/
Runner.java
File metadata and controls
75 lines (62 loc) · 1.66 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
package examples7;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Runner {
private Account acc1 = new Account();
private Account acc2 = new Account();
private Lock lock1 = new ReentrantLock();
private Lock lock2 = new ReentrantLock();
private void aquireLocks(Lock l1, Lock l2) throws InterruptedException {
while(true) {
//Acquire locks
boolean gotFirstLock = false;
boolean gotSecondLock = false;
try {
gotFirstLock = l1.tryLock();
gotSecondLock = l2.tryLock();
} finally {
if(gotFirstLock && gotSecondLock) {
return;
}
if(gotFirstLock) {
l1.unlock();
}
if(gotSecondLock) {
l2.unlock();
}
}
//Locks not acquired
Thread.sleep(1);
}
}
public void firstThread() throws InterruptedException {
Random r = new Random();
for (int i = 0; i < 10000; i++) {
aquireLocks(lock1, lock2);
try {
Account.transfer(acc1, acc2, r.nextInt(100));
} finally {
lock1.unlock();
lock2.unlock();
}
}
}
public void secondThread() throws InterruptedException {
Random r = new Random();
for (int i = 0; i < 10000; i++) {
aquireLocks(lock2, lock1);
try {
Account.transfer(acc2, acc1, r.nextInt(100));
} finally {
lock1.unlock();
lock2.unlock();
}
}
}
public void finished() {
System.out.println("Account 1 balance: " + acc1.getBalance());
System.out.println("Account 2 balance: " + acc2.getBalance());
System.out.println("Total Balance: " + (acc1.getBalance() + acc2.getBalance()));
}
}