-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTestThreadCoopearation.java
More file actions
52 lines (46 loc) · 1.3 KB
/
TestThreadCoopearation.java
File metadata and controls
52 lines (46 loc) · 1.3 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
class Customer {
private int amount = 10000;
synchronized void withdraw(int amount) {
System.out.println("going to withdraw...");
while (this.amount < amount) {
System.out.println("Less balance; waiting for deposit...");
try {
wait();
} catch (Exception e) {
}
}
this.amount -= amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount) {
System.out.println("going to deposit...");
this.amount += amount;
System.out.println("deposit completed... ");
notifyAll();
}
}
class TestThreadCooperation {
public static void main(String args[]) {
final Customer c = new Customer();
new Thread() {
public void run() {
c.withdraw(15000);
}
}.start(); // Thread-1
new Thread() {
public void run() {
c.withdraw(11000);
}
}.start(); // Thread-1
new Thread() {
public void run() {
c.withdraw(10000);
}
}.start(); // Thread-1
new Thread() {
public void run() {
c.deposit(1000);
}
}.start(); // Thread-2
}
}