|
| 1 | +package exercise_30_08; |
| 2 | + |
| 3 | +import java.util.concurrent.ExecutorService; |
| 4 | +import java.util.concurrent.Executors; |
| 5 | +import java.util.concurrent.locks.Condition; |
| 6 | +import java.util.concurrent.locks.Lock; |
| 7 | +import java.util.concurrent.locks.ReentrantLock; |
| 8 | + |
| 9 | +public class Exercise_30_08 { |
| 10 | + private static Account account = new Account(); |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + ExecutorService executor = Executors.newFixedThreadPool(2); |
| 14 | + executor.execute(new DepositTask()); |
| 15 | + executor.execute(new WithdrawTask()); |
| 16 | + executor.shutdown(); |
| 17 | + |
| 18 | + System.out.println("Thread 1\t\tThread 2\t\tBalance"); |
| 19 | + } |
| 20 | + |
| 21 | + public static class DepositTask implements Runnable { |
| 22 | + @Override |
| 23 | + public void run() { |
| 24 | + try { |
| 25 | + while(true) { |
| 26 | + account.deposit((int)(Math.random() * 10) + 1); |
| 27 | + Thread.sleep(1000); |
| 28 | + } |
| 29 | + } |
| 30 | + catch (InterruptedException ex) { |
| 31 | + ex.printStackTrace(); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public static class WithdrawTask implements Runnable { |
| 37 | + @Override |
| 38 | + public void run() { |
| 39 | + while(true) { |
| 40 | + account.withdraw((int)(Math.random() * 10) + 1); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + private static class Account { |
| 46 | + private int balance = 0; |
| 47 | + |
| 48 | + public int getBalance() { |
| 49 | + return balance; |
| 50 | + } |
| 51 | + |
| 52 | + public synchronized void withdraw(int amount) { |
| 53 | + try { |
| 54 | + while(balance < amount) { |
| 55 | + System.out.println("\t\t\tWait for a deposit"); |
| 56 | + wait(); |
| 57 | + } |
| 58 | + balance -= amount; |
| 59 | + System.out.println("\t\t\tWithdraw " + amount + "\t\t" + getBalance()); |
| 60 | + } |
| 61 | + catch (InterruptedException ex) { |
| 62 | + ex.printStackTrace(); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + public synchronized void deposit(int amount) { |
| 67 | + balance += amount; |
| 68 | + System.out.println("Deposit " + amount + "\t\t\t\t\t" + getBalance()); |
| 69 | + |
| 70 | + notifyAll(); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments