Java Reference
In-Depth Information
Customer #1 is trying to get a table.
Customer #1 got a table.
Customer #2 is trying to get a table.
Customer #1 will eat for 17 seconds.
Customer #2 got a table.
Customer #2 will eat for 19 seconds.
Customer #3 is trying to get a table.
...
Listing 6-34 contains the code for a RestaurantCustomer class whose object represents a customer in a
restaurant. The run() method of the customer thread gets a table from the restaurant, eats for a random amount of
time, and returns the table to the restaurant. When you run the Restaurant class, you may get similar but not the
same output. You may observe that you have created a restaurant with only two tables and five customers are trying to
eat. At any given time, only two customers are eating, as shown by the output.
Listing 6-34. A RestaurantCustomer Class to Represent a Customer in a Restaurant
// RestaurantCustomer.java
package com.jdojo.threads;
import java.util.Random;
class RestaurantCustomer extends Thread {
private Restaurant r;
private int customerID;
private static final Random random = new Random();
public RestaurantCustomer(Restaurant r, int customerID) {
this.r = r;
this.customerID = customerID;
}
public void run() {
r.getTable(this.customerID); // Get a table
try {
// Eat for some time. Use number between 1 and 30 seconds
int eatingTime = random.nextInt(30) + 1 ;
System.out.println("Customer #" + this.customerID +
" will eat for " + eatingTime +
" seconds.");
Thread.sleep(eatingTime * 1000);
System.out.println("Customer #" + this.customerID +
" is done eating.");
}
catch(InterruptedException e) {
e.printStackTrace();
}
finally {
r.returnTable(this.customerID);
}
}
}
Search WWH ::




Custom Search