|
| 1 | +class BankAccount { |
| 2 | + private int balance = 1000; |
| 3 | + |
| 4 | + // Synchronized method to avoid race condition |
| 5 | + public synchronized void withdraw(int amount, String threadName) { |
| 6 | + System.out.println(threadName + " is trying to withdraw $" + amount); |
| 7 | + |
| 8 | + if (balance >= amount) { |
| 9 | + System.out.println(threadName + " is about to withdraw..."); |
| 10 | + try { |
| 11 | + Thread.sleep(100); // simulate time delay |
| 12 | + } catch (InterruptedException e) { |
| 13 | + System.out.println("Interrupted!"); |
| 14 | + } |
| 15 | + balance -= amount; |
| 16 | + System.out.println(threadName + " completed withdrawal. Remaining balance: $" + balance); |
| 17 | + } else { |
| 18 | + System.out.println("Not enough balance for " + threadName + " to withdraw $" + amount); |
| 19 | + } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +class WithdrawThread extends Thread { |
| 24 | + private BankAccount account; |
| 25 | + private int amount; |
| 26 | + |
| 27 | + public WithdrawThread(BankAccount account, int amount, String name) { |
| 28 | + super(name); // Set thread name |
| 29 | + this.account = account; |
| 30 | + this.amount = amount; |
| 31 | + } |
| 32 | + |
| 33 | + public void run() { |
| 34 | + account.withdraw(amount, Thread.currentThread().getName()); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +class ThreadSyncDemo { |
| 39 | + public static void main(String[] args) { |
| 40 | + BankAccount account = new BankAccount(); |
| 41 | + |
| 42 | + // Two threads trying to withdraw money from the same account |
| 43 | + WithdrawThread t1 = new WithdrawThread(account, 700, "Thread-1"); |
| 44 | + WithdrawThread t2 = new WithdrawThread(account, 500, "Thread-2"); |
| 45 | + |
| 46 | + t1.start(); |
| 47 | + t2.start(); |
| 48 | + } |
| 49 | +} |
| 50 | + |
0 commit comments