-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnsynchBankTest.java
More file actions
34 lines (32 loc) · 1.11 KB
/
UnsynchBankTest.java
File metadata and controls
34 lines (32 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
package unsynch;
/**
* This program shows data corruption when multiple threads access a data structure.
*
* @author Cay Horstmann
* @version 1.31 2015-06-21
*/
public class UnsynchBankTest {
public static final int N_ACCOUNTS = 100;
public static final double INITIAL_BALANCE = 1000;
public static final double MAX_AMOUNT = 1000;
public static final int DELAY = 10;
public static void main(String[] args) {
Bank bank = new Bank(N_ACCOUNTS, INITIAL_BALANCE);
for (int i = 0; i < N_ACCOUNTS; i++) {
int fromAccount = i;
Runnable r = () -> {
try {
while (true) {
int toAccount = (int) (bank.size() * Math.random());
double amount = MAX_AMOUNT * Math.random();
bank.transfer(fromAccount, toAccount, amount);
Thread.sleep((int) (DELAY * Math.random()));
}
} catch (InterruptedException ignored) {
}
};
Thread t = new Thread(r);
t.start();
}
}
}