Java Reference
In-Depth Information
Listing 6-33 has the code for a Restaurant class. It takes the number of tables available in a restaurant and creates
a semaphore, which has the number of permits that is equal to the number of tables. A customer uses its getTable()
and returnTable() methods to get and return a table, respectively. Inside the getTable() method, you acquire a
permit. If a customer calls the getTable() method and no table is available, he must wait until one becomes available.
This class depends on a RestaurantCustomer class that is declared in Listing 6-34.
Listing 6-33. A Restaurant Class, Which Uses a Semaphore to Control Access to Tables
// Restaurant.java
package com.jdojo.threads;
import java.util.concurrent.Semaphore;
public class Restaurant {
private Semaphore tables;
public Restaurant(int tablesCount) {
// Create a semaphore using number of tables we have
this.tables = new Semaphore(tablesCount);
}
public void getTable(int customerID) {
try {
System.out.println("Customer #" + customerID + " is trying to get a table.");
// Acquire a permit for a table
tables.acquire();
System.out.println("Customer #" + customerID + " got a table.");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public void returnTable(int customerID) {
System.out.println("Customer #" + customerID + " returned a table.");
tables.release();
}
public static void main(String[] args) {
// Create a restaurant with two dining tables
Restaurant restaurant = new Restaurant(2);
// Create five customers
for (int i = 1; i <= 5; i++) {
RestaurantCustomer c = new RestaurantCustomer(restaurant, i);
c.start();
}
}
}
Search WWH ::




Custom Search