-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunning.java
More file actions
71 lines (60 loc) · 2.27 KB
/
Running.java
File metadata and controls
71 lines (60 loc) · 2.27 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
package com.jspiders.multithreading.thread;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Running {
private Account acc1 = new Account();
private Account acc2 = new Account();
private Lock lock1 = new ReentrantLock();
private Lock lock2 = new ReentrantLock();
private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedException {
while (true) {
// Acquire locks
boolean gotFirstLock = false;
boolean gotSecondLock = false;
try {
gotFirstLock = firstLock.tryLock();
gotSecondLock = secondLock.tryLock();
} finally {
if (gotFirstLock && gotSecondLock) return;
else if (gotFirstLock) firstLock.unlock();
else if (gotSecondLock) secondLock.unlock();
}
// Locks not acquired
Thread.sleep(1);
}
}
//firstThread runs
public void firstThread() throws InterruptedException {
Random random = new Random();
for (int i = 0; i < 10000; i++) {
acquireLocks(lock1, lock2);
try {
Account.transfer(acc1, acc2, random.nextInt(100));
} finally {
lock1.unlock();
lock2.unlock();
}
}
}
//SecondThread runs
public void secondThread() throws InterruptedException {
Random random = new Random();
for (int i = 0; i < 10000; i++) {
acquireLocks(lock2, lock1);
try {
Account.transfer(acc2, acc1, random.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("Account 3 balance: " + acc2.getBalance());
System.out.println("Account 1 balance: " + acc1.getBalance());
System.out.println("Total balance: " + (acc1.getBalance() + acc2.getBalance()));
}
}