forked from slgobinath/Java-Helps-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransaction.java
More file actions
32 lines (29 loc) · 926 Bytes
/
Transaction.java
File metadata and controls
32 lines (29 loc) · 926 Bytes
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
public class Transaction extends Thread {
private final String id;
private final Account from;
private final Account to;
private final double amount;
public Transaction(String id, Account from, Account to, double amount) {
this.id = id;
this.from = from;
this.to = to;
this.amount = amount;
}
@Override
public void run() {
// Acquire the lock of Account 'from'
synchronized (from) {
from.withdraw(amount);
try {
Thread.sleep(500);
} catch (InterruptedException e) { }
// Acquire the lock of Account 'to'
synchronized (to) {
to.deposit(amount);
}
// Release the lock of Account 'to'
}
// Release the lock of Account 'from'
System.out.println(amount + "is transfered from " + from + " to " + to);
}
}