Commit d5c45c78 authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Moving the operation back into the run method. It can't be fixed with...

[Ch15] Moving the operation back into the run method. It can't be fixed with synchronisation like this though....
parent 8b72c7b5
Loading
Loading
Loading
Loading
+18 −14
Changes for src/main/java/ch15/ryanmonica/RyanAndMonicaTest.java: 18 added lines, 14 removed lines.
Original line number Diff line number Diff line
@@ -31,29 +31,19 @@ class RyanAndMonicaJob implements Runnable {

  public void run() {
    for (int i = 0; i < 10; i++) {
      account.makeWithdrawal(10, name);
      if (account.getBalance() < 0) {
        System.out.println("Overdrawn!");
      }
    }
      goShopping();
    }
  }

class BankAccount {
  private int balance = 100;
  public int getBalance() {
    return balance;
  }

  public void makeWithdrawal(int amount, String name) {
    if (balance >= amount) {
  private void goShopping() {
    if (account.getBalance() >= 10) {
      System.out.println(name + " is about to withdraw");
      try {
        System.out.println(name + " is going to sleep");
        Thread.sleep(500);
      } catch (InterruptedException ex) {ex.printStackTrace();}
      System.out.println(name + " woke up.");
      balance = balance - amount;
      account.withdraw(10);
      System.out.println(name + " completes the withdrawal");
    } else {
      System.out.println("Sorry, not enough for " + name);
@@ -61,4 +51,18 @@ class BankAccount {
  }
}

class BankAccount {
  private int balance = 100;
  public int getBalance() {
    return balance;
  }

  public void withdraw(int amount) {
    balance = balance - amount;
    if (balance < 0) {
      System.out.println("Overdrawn!");
    }
  }
}