InterthreadCommunitcationDemo.java
class InterthreadCommunitcationDemo
{
public static void main(String args[])
{
final BankAccount bankAccount = new BankAccount();
new Thread("Thread 1")
{
public void run()
{
bankAccount.withdraw(50000);
}
}.start();
new Thread("Thread 2")
{
public void run()
{
bankAccount.deposit(80000);
}
}.start();
}
}
BankAccount.java
class BankAccount
{
private int amount = 10000;
synchronized void withdraw(int amount)
{
System.out.println("Going to withdraw...");
if (this.amount < amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
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... ");
notify();
}
}
Output
Going to withdraw...
Less balance; waiting for deposit...
Going to deposit...
Deposit completed...
Withdraw completed...
Refer:
https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Object.html
Click the below link to download the code:
No comments:
Post a Comment