-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
49 lines (38 loc) · 1.37 KB
/
Main.java
File metadata and controls
49 lines (38 loc) · 1.37 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
package example1;
import java.math.BigDecimal;
public class Main {
public static Thread createActor(final BankAccount account, final BigDecimal withdrawAmount) {
Thread th = new Thread(new Runnable() {
public void run() {
while (true) {
if (!account.withdraw(withdrawAmount))
break;
incrementWithdrawn(withdrawAmount);
}
}
});
th.start();
return th;
}
public static void main(String[] args) throws InterruptedException {
BankAccount account = new BankAccount(new BigDecimal(400000));
Thread thread1 = createActor(account, new BigDecimal(4));
Thread thread2 = createActor(account, new BigDecimal(10));
thread1.join();
thread2.join();
System.out.println("New amount: " + account.getAmount().toString());
System.out.println("Total withdrawn: " + getWithdrawn().toString());
}
private static final Object lock = new Object();
private static BigDecimal totalWithDrawn = BigDecimal.ZERO;
static void incrementWithdrawn(BigDecimal amount) {
synchronized (lock) {
totalWithDrawn = totalWithDrawn.add(amount);
}
}
static BigDecimal getWithdrawn() {
synchronized (lock) {
return totalWithDrawn;
}
}
}