I'm trying to simulate a bank's service. So far I can randomly generate customers with random times, and the cashiers will serve them if they are not busy. My problem comes when the simulation is supposed to end...it won't. Customers stop being generated, but the cashier keep waiting for customers. I've tried different approaches, but failed. This is the code before attempting different solutions.
This is the CustomerGenerator:
@Override
public void run() {
while (currentTime != openTime) {
double accept = Math.random();
if (accept >= 0.6) {
addCustomerToQueue();
System.out.println("Customer in line.");
} else {
System.out.println("Waiting for a customer.");
}
try {
currentTime += 1000;
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private synchronized void addCustomerToQueue() {
Customer customer = new Customer(placeInLine + 1);
this.customerLinkedList.add(customer);
placeInLine++;
notify();
}
synchronized Customer getNextCustomer() throws InterruptedException {
notify();
while (customerLinkedList.size() == 0) {
wait();
}
return customerLinkedList.poll();
}
This is the Cashier:
@Override
public void run() {
try {
while (true) {
Customer customer = generator.getNextCustomer();
int customerServingNumber = customer.getServingNumber();
double customerServingTime = customer.getServingTime();
System.out.println(cashierName + " serving " + customerServingNumber + " for " + getServingTime(customerServingTime));
Thread.sleep(customerServingNumber * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}