Commit 15cfb43d authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Updating Ryan and Monica example - firstly with Executors, and secondly...

[Ch15] Updating Ryan and Monica example - firstly with Executors, and secondly to more clearly show they're sharing the same BankAccount object.
parent add302a2
Loading
Loading
Loading
Loading
+23 −14
Changes for src/main/java/ch15/TestRyanAndMonica.java: 23 added lines, 14 removed lines.
Original line number Diff line number Diff line
package ch15;

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

public class TestRyanAndMonica {
  public static void main(String[] args) {
    RyanAndMonicaJob theJob = new RyanAndMonicaJob();
    Thread one = new Thread(theJob);
    Thread two = new Thread(theJob);
    one.setName("Ryan");
    two.setName("Monica");
    one.start();
    two.start();
    BankAccount account = new BankAccount();
    RyanAndMonicaJob ryan = new RyanAndMonicaJob("Ryan", account);
    RyanAndMonicaJob monica = new RyanAndMonicaJob("Monica", account);
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(ryan);
    executor.execute(monica);
    executor.shutdown();
  }
}

class RyanAndMonicaJob implements Runnable {
  private final BankAccount account = new BankAccount();
  private final String name;
  private final BankAccount account;

  RyanAndMonicaJob(String name, BankAccount account) {
    this.name = name;
    this.account = account;
  }

  public void run() {
    for (int i = 0; i < 10; i++) {
@@ -26,24 +35,24 @@ class RyanAndMonicaJob implements Runnable {

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

class BankAccount {
  private int balance = 100;
  private int balance = 50;

  public int getBalance() {
    return balance;