BankAccount.java
85 linesjava
DOWNLOAD
1// Aim: Program to perform Multithreading operations (Bank BankAccountTask).
2import java.util.Scanner;
3
4class BankAccountTask {
5    private int accountNo;
6    private double balance;
7
8    public BankAccountTask(int accountNo, double initialBalance) {
9        this.accountNo = accountNo;
10        this.balance = initialBalance;
11    }
12
13    public synchronized void deposit(double amount) {
14        balance += amount;
15        System.out.println("Deposited: " + amount + ", New Balance: " + balance);
16    }
17
18    public synchronized void withdraw(double amount) {
19        if (balance >= amount) {
20            balance -= amount;
21            System.out.println("Withdrawn: " + amount + ", New Balance: " + balance);
22        } else {
23            System.out.println("Insufficient balance for withdrawal of " + amount);
24        }
25    }
26
27    public void displayBalance() {
28        System.out.println("BankAccountTask No: " + accountNo + ", Balance: " + balance);
29    }
30}
31
32class DepositThread extends Thread {
33    private BankAccountTask account;
34    private double amount;
35
36    public DepositThread(BankAccountTask account, double amount) {
37        this.account = account;
38        this.amount = amount;
39    }
40
41    public void run() {
42        account.deposit(amount);
43    }
44}
45
46class WithdrawThread extends Thread {
47    private BankAccountTask account;
48    private double amount;
49
50    public WithdrawThread(BankAccountTask account, double amount) {
51        this.account = account;
52        this.amount = amount;
53    }
54
55    public void run() {
56        account.withdraw(amount);
57    }
58}
59
60public class BankAccount {
61    public static void main(String[] args) {
62        Scanner scanner = new Scanner(System.in);
63
64        System.out.print("Enter BankAccountTask Number: ");
65        int accountNo = scanner.nextInt();
66
67        System.out.print("Enter Initial Balance: ");
68        double initialBalance = scanner.nextDouble();
69
70        BankAccountTask account = new BankAccountTask(accountNo, initialBalance);
71
72        System.out.print("Enter amount to deposit: ");
73        double depositAmount = scanner.nextDouble();
74
75        System.out.print("Enter amount to withdraw: ");
76        double withdrawAmount = scanner.nextDouble();
77
78        DepositThread depositThread = new DepositThread(account, depositAmount);
79        WithdrawThread withdrawThread = new WithdrawThread(account, withdrawAmount);
80
81        depositThread.start();
82        withdrawThread.start();
83        scanner.close();
84    }
85}