Commit 4c29a323 authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Ryan and Monica solution in BankAccount

parent 7518478d
Loading
Loading
Loading
Loading
+57 −0
Changes for src/main/java/ch15/ryanmonica/RyanAndMonicaBankChecksTest.java: 57 added lines, 0 removed lines.
Original line number Diff line number Diff line
package ch15.ryanmonica;

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

public class RyanAndMonicaBankChecksTest {
  public static void main(String[] args) throws InterruptedException {
    BankAccountChecks account = new BankAccountChecks();
    RyanAndMonicaBankChecksJob ryan = new RyanAndMonicaBankChecksJob("Ryan", account);
    RyanAndMonicaBankChecksJob monica = new RyanAndMonicaBankChecksJob("Monica", account);
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(ryan);
    executor.execute(monica);
    executor.shutdown();
  }
}

class RyanAndMonicaBankChecksJob implements Runnable {
  private final String name;
  private final BankAccountChecks account;

  RyanAndMonicaBankChecksJob(String name, BankAccountChecks account) {
    this.name = name;
    this.account = account;
  }

  public void run() {
    for (int i = 0; i < 5; i++) {
      goShopping(10);
    }
  }

  private void goShopping(int amount) {
    System.out.println(name + " is about to spend");
    account.spend(name, amount);
    System.out.println(name + " finishes spending");
  }
}

class BankAccountChecks {
  private int balance = 50;

  public int getBalance() {
    return balance;
  }

  public synchronized void spend(String name, int amount) {
    if (getBalance() >= amount) {
      balance = balance - amount;
      if (balance < 0) {
        System.out.println("Overdrawn!");
      }
    } else {
      System.out.println("Sorry, not enough for " + name);
    }
  }
}
+6 −6

File changed.

Contains only whitespace changes.