import java.util.LinkedList; import java.util.Queue; /** * implements the running of the bank * The principle thing that happens in the bank * is in the run method */ public class Bank implements BankInterface, Runnable { /** The queue of customers */ Queue customerQueue; /** Allows stopping the separate running thread. */ private volatile boolean exit = false; /** Just record when the bank opened so you can say * how long it was open when it closed. */ private long openingTime; /** A customer came in. Add it to the queue */ @Override public void enteringCustomer(Customer customer) { customerQueue.add(customer); } /** Initialize the bank */ public Bank() { customerQueue = new LinkedList(); } /** Close the back. That is stop accepting new customers */ public void closeBank() { exit=true; } /** Open the doors. */ public void openBank() { openingTime = System.nanoTime(); (new Thread(this)).start(); } /** * All that happens in the bank is that the "teller" checks the * customer queue. If q not empty the teller deals with the * customer. */ @Override public void run() { while(true) { System.out.println(String.format("%.1f Teller tooking at queue of length %d", (System.nanoTime()-openingTime) / 1000000000.0, customerQueue.size())); if (customerQueue.isEmpty()) { // if no customers wait before checking is there are customers try { Thread.sleep(100); } catch (Exception e) {} if (exit) break; } else { // have a customer so remover from customer q Customer customer = customerQueue.poll(); // Work with the customer for some amount of time // sleep can throw an exception try { Thread.sleep(customer.transactionLength()*100); } catch (Exception e) {} // Now completed with the customer, so tell the customer that customer.completed(); double tt = (System.nanoTime()-openingTime) / 1000000000.0; System.out.println(String.format(" %.1f Processed customer which took time 0.%d", tt, customer.transactionLength())); } } } }