-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRyanAndMonicaJob.java
More file actions
63 lines (45 loc) · 1.57 KB
/
RyanAndMonicaJob.java
File metadata and controls
63 lines (45 loc) · 1.57 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
class BankAccount {
private int acc_balance = 100;
public int getBalance() {
return acc_balance;
}
public void withdraw(int amount) {
acc_balance = acc_balance - amount;
}
}
public class RyanAndMonicaJob implements Runnable {
private BankAccount account = new BankAccount();
public static void main(String[] args) {
RyanAndMonicaJob theJob = new RyanAndMonicaJob();
Thread one = new Thread(theJob);
Thread two = new Thread(theJob);
one.setName("Ryan");
two.setName("Monica");
one.start();
two.start();
}
public void run() {
for (int i = 0; i < 10; i++) {
makeWithdraw(10);
if (account.getBalance() < 0) {
System.out.println("Overdrawn");
}
}
}
public void makeWithdraw(int amount) {
if (account.getBalance() >= amount) {
System.out.println(Thread.currentThread().getName() + " is about to withdraw");
try {
System.out.println(Thread.currentThread().getName() + " is going to sleep");
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(Thread.currentThread().getName() + " woke up");
account.withdraw(amount);
System.out.println(Thread.currentThread().getName() + " completed the withdraw");
} else {
System.out.println("Sorry no enough money for " + Thread.currentThread().getName());
}
}
}