Java Program (BankingProcessDemo)
class BankAccount
{
private int balance = 0;
public synchronized void deposit(int amount)
{
balance += amount;
System.out.println("Deposited: " + amount + ", Current Balance: " + balance);
notify();
}
public synchronized void withdraw(int amount) throws InterruptedException
{
while (balance < amount)
{
System.out.println("Insufficient balance for withdrawal. Waiting for deposit...");
wait();
}
balance -= amount;
System.out.println("Withdrawn: " + amount + ", Remaining Balance: " + balance);
}
}
class Depositor extends Thread
{
private BankAccount account;
private int amount;
public Depositor(BankAccount account, int amount)
{
this.account = account;
this.amount = amount;
}
public void run()
{
account.deposit(amount);
}
}
class Withdrawer extends Thread
{
private BankAccount account;
private int amount;
public Withdrawer(BankAccount account, int amount)
{
this.account = account;
this.amount = amount;
}
public void run()
{
try
{
account.withdraw(amount);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
System.err.println("Withdrawer interrupted");
}
}
}
public class BankingProcessDemo
{
public static void main(String[] args)
{
BankAccount account = new BankAccount();
Depositor depositor = new Depositor(account, 2000);
Withdrawer withdrawer = new Withdrawer(account, 1500);
depositor.start();
withdrawer.start();
}
}
0 Comments