-
Notifications
You must be signed in to change notification settings - Fork 25
/
synchronization.java
65 lines (60 loc) · 1.49 KB
/
synchronization.java
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
package Threads;
class Customer
{
int amount = 10000;
synchronized void withdraw(int amount)
{
System.out.println("Available Balance: " + this.amount);
System.out.println("About to withdraw: " + amount);
if (this.amount < amount)
{
System.out.println("Insufficient Balance – Need to Deposit.");
try
{
wait();
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}
this.amount -= amount;
System.out.println("Detected amaount: " + amount);
System.out.println("Balance amount : " + this.amount);
}
synchronized void deposit(int amount)
{
System.out.println("About to deposit: " + amount);
this.amount += amount;
System.out.println("Available Balance: " + this.amount);
System.out.println("Transaction completed.\n");
notify();
}
}
class Test
{
public static void main(String arg[])
{
final Customer c = new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}