0% found this document useful (0 votes)
3 views2 pages

Java 11

Uploaded by

jayshivray519
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Java 11

Uploaded by

jayshivray519
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practical no 11

public class BankAccount {


int balance;
public BankAccount(int initialBalance) {
[Link] = initialBalance;
}
public synchronized void deposit(String threadName, int amount) {
balance += amount;
[Link](threadName + " deposited $" + amount + ". Current balance: $" +balance);
}
public synchronized void withdraw(String threadName, int amount) {
if (balance >= amount) {
balance -= amount;
[Link](threadName + " withdrew $" + amount + ". Current balance: $" balance);
}
else {
[Link](threadName + " attempted to withdraw $" + amount + " but insufficient funds.
Current balance: $" + balance);
}
}
public synchronized void checkBalance(String threadName) {
[Link](threadName + " checked the balance. Current balance: $" + balance);
}
}

public class BankingSystem {


public static void main(String[] args) {
BankAccount sharedAccount = new BankAccount(1000); // Shared bank account with initial
balance of $1000
Thread t1 = new BankingThread(sharedAccount, "deposit", 500, "Thread-1");
Thread t2 = new BankingThread(sharedAccount, "withdraw", 300, "Thread-2");
Thread t3 = new BankingThread(sharedAccount, "check", 0, "Thread-3");
Thread t4 = new BankingThread(sharedAccount, "withdraw", 1500, "Thread-4"); //
Withdrawal exceeding balance
Thread t5 = new BankingThread(sharedAccount, "deposit", 200, "Thread-5");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
try {
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}

[Link]("All operations completed. Final balance: $" + [Link]);


}
}

public class BankingThread


extends Thread {
private BankAccount account;
private String operation;
private int amount;
public BankingThread(BankAccount account, String operation, int amount, String name) {
super(name);
[Link] = account;
[Link] = operation;
[Link] = amount;
}
public void run() {
switch ([Link]()) {
case "deposit":
[Link](getName(), amount);
break;
case "withdraw":
[Link](getName(), amount);
break;
case "check":
[Link](getName());
break;
default:
[Link](getName() + " performed an invalid operation.");
} } }

You might also like