forked from JavaOPs/basejava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainDeadLockExample.java
More file actions
73 lines (61 loc) · 2.02 KB
/
MainDeadLockExample.java
File metadata and controls
73 lines (61 loc) · 2.02 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
package ru.javaops.webapp;
public class MainDeadLockExample {
public static void main(String[] args) {
Account accountA = new Account(1, "AAA", 100000.);
Account accountB = new Account(2, "BBB", 50000.);
for (int i = 1; i < 100000; i++) {
Thread thread01 = new Thread(() -> {
doTransfer(accountA, accountB, 1);
System.out.println(accountA.getAmount() + " " + accountB.getAmount());
});
thread01.start();
Thread thread02 = new Thread(() -> {
doTransfer(accountB, accountA, 1);
System.out.println(accountA.getAmount() + " " + accountB.getAmount());
});
thread02.start();
}
}
private static void doTransfer(Account fromAcc, Account toAcc, double amount) {
synchronized (fromAcc) {
if (fromAcc.getAmount() < amount) {
System.out.println("Error, not enough amount at account ID: " + fromAcc.getId());
} else {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (toAcc) {
fromAcc.credit(amount);
toAcc.debit(amount);
}
}
}
}
private static class Account {
private final int id;
private final String owner;
private double amount;
Account(int id, String owner, double amount) {
this.id = id;
this.owner = owner;
this.amount = amount;
}
public int getId() {
return id;
}
public String getOwner() {
return owner;
}
public double getAmount() {
return amount;
}
private void debit(double amount) {
this.amount += amount;
}
private void credit(double amount) {
this.amount -= amount;
}
}
}