Pages

Wednesday, 1 March 2017

Chapter 30 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

30.8 (Account synchronization) Rewrite Listing 30.6, ThreadCooperation.java,
using the object’s wait() and notifyAll() methods.


import java.util.concurrent.*;

public class Exercise08 {
 private static Account account = new Account();

 public static void main(String[] args) {
  // Create a thread pool with two threads
  ExecutorService executor = Executors.newFixedThreadPool(2);
  executor.execute(new DepositTask());
  executor.execute(new WithdrawTask());
  executor.shutdown();

  System.out.println("Thread 1\t\tThread 2\t\tBalance");
 }

 public static class DepositTask implements Runnable {
  @Override
  // Keep adding an amount to the account
  public void run() {
   try { // Purposely delay it to let the withdraw method proceed
    while (true) {
     account.deposit((int) (Math.random() * 10) + 1);
     Thread.sleep(1000);
    }
   } catch (InterruptedException ex) {
    ex.printStackTrace();
   }
  }
 }

 public static class WithdrawTask implements Runnable {
  @Override
  // Keep subtracting an amount from the account
  public void run() {
   while (true) {
    account.withdraw((int) (Math.random() * 10) + 1);
   }
  }
 }

 // An inner class for account
 private static class Account {

  private int balance = 0;

  public int getBalance() {
   return balance;
  }

  public synchronized void withdraw(int amount) {
   try {
    while (balance < amount) {
     System.out.println("\t\t\tWait for a deposit");
     this.wait();
    }

    balance -= amount;
    System.out.println("\t\t\tWithdraw " + amount + "\t\t" + getBalance());
   } catch (InterruptedException ex) {
    ex.printStackTrace();
   }
  }

  public synchronized void deposit(int amount) {
   balance += amount;
   System.out.println("Deposit " + amount + "\t\t\t\t\t" + getBalance());
   notifyAll();
  }
 }
}

No comments:

Post a Comment