-
Notifications
You must be signed in to change notification settings - Fork 3
/
Customer.java
83 lines (73 loc) · 2.2 KB
/
Customer.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package bank;
import net.jcip.annotations.GuardedBy;
import java.util.ConcurrentModificationException;
import java.util.Map;
import java.util.Random;
/**
* Created by kennylbj on 16/8/27.
* A runnable to transfer money to
* other account randomly.
*/
class Customer implements Runnable {
@GuardedBy("accounts")
private final Map<Integer, Integer> accounts;
private final int id;
private final int threshold;
private final Random random;
//volatile guarantee the memory visibility
private volatile boolean stop = false;
//count the transfer times. single-thread-access guarantee
private int count;
private int poorTimes;
Customer(int id, Map<Integer, Integer> accounts, int threshold) {
this.id = id;
this.accounts = accounts;
this.threshold = threshold;
this.random = new Random();
this.count = 0;
this.poorTimes = 0;
}
void stop() {
this.stop = true;
}
int getCount() {
if (!stop) {
throw new ConcurrentModificationException("Can't not access count");
}
return count;
}
int getPoorTimes() {
if (!stop) {
throw new ConcurrentModificationException("Can't not access poorTimes");
}
return poorTimes;
}
@Override
public void run() {
while (!stop) {
//accounts's size is a constant we so don't need to synchronize it
int size = accounts.size();
int pickOne = random.nextInt(size);
//pick myself
if (pickOne == id) {
continue;
}
//transfer a random amount with money [1, threshold]
int transfer = random.nextInt(threshold) + 1;
//critical section
synchronized (accounts) {
int from = accounts.get(id);
if (from < transfer) {
poorTimes++;
continue;
}
int to = accounts.get(pickOne);
from -= transfer;
to += transfer;
accounts.put(id, from);
accounts.put(pickOne, to);
count++;
}
}
}
}