Commit 706e643e authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Book version of Ryan and Monica

parent 24cf64c6
Loading
Loading
Loading
Loading
+17 −25
Changes for src/main/java/ch15/RyanAndMonicaTest.java: 17 added lines, 25 removed lines.
Original line number Diff line number Diff line
package ch15;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class BankAccount {
  private int balance = 100;

  public int getBalance() {
    return balance;
  }

  public void withdraw(int amount) {
    balance = balance - amount;
  }
}

public class RyanAndMonicaTest {
  public static void main(String[] args) {
    BankAccount account = new BankAccount();
@@ -19,7 +30,6 @@ public class RyanAndMonicaTest {
class RyanAndMonicaJob implements Runnable {
  private final String name;
  private final BankAccount account;
  private final Random randomGenerator = new Random();

  RyanAndMonicaJob(String name, BankAccount account) {
    this.name = name;
@@ -27,7 +37,7 @@ class RyanAndMonicaJob implements Runnable {
  }

  public void run() {
    while (account.getBalance() > 0) {
    for (int i = 0; i < 10; i++) {
      makeWithdrawal(10);
      if (account.getBalance() < 0) {
        System.out.println("Overdrawn!");
@@ -37,35 +47,17 @@ class RyanAndMonicaJob implements Runnable {

  private void makeWithdrawal(int amount) {
    if (account.getBalance() >= amount) {
      System.out.printf("%s is about to withdraw $%d. Current balance: $%d%n", name, amount, account.getBalance());
      System.out.println(name + " is about to withdraw");
      try {
        System.out.println(name + " is going to sleep");
        sleepForRandomTime();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
        Thread.sleep(500);
      } catch (InterruptedException ex) {ex.printStackTrace();}
      System.out.println(name + " woke up.");
      account.withdraw(amount);
      System.out.printf("%s completes the withdrawal of $%d. New balance: $%d%n", name, amount, account.getBalance());
      System.out.println(name + " completes the withdrawal");
    } else {
      System.out.println("Sorry, not enough for " + name);
    }
  }

  private void sleepForRandomTime() throws InterruptedException {
    Thread.sleep(randomGenerator.nextInt(500));
  }
}

class BankAccount {
  private int balance = 50;

  public int getBalance() {
    return balance;
  }

  public void withdraw(int amount) {
    balance = balance - amount;
  }
}