Working with Threads. Thinking in Java Exercise
I'm sorry for the code apperance. One more time original Restaurant.java I
hope i won't break
-----------------------------------------------------------------------------------------------------------
class Order
{
public static int index = 0;
private int count = ++index;
public Order( )
{
if ( index > 10 )
{
java.lang.System.out.println( "Out of food. Closing..." );
java.lang.System.exit( 0 );
}
}
public String toString()
{
return "order #" + count;
}
}
class Waitperson extends Thread
{
private Restaurant restaurant;
public Waitperson( Restaurant rest )
{
super( );
restaurant = rest;
start( );
}
public void run( )
{
while( true )
{
if( restaurant.order == null)
{
synchronized( this )
{
try
{
wait( );
}
catch( java.lang.InterruptedException ex )
{
throw new RuntimeException( );
}
}
}
System.out.println( "Waitperson got " + restaurant.order );
restaurant.order = null;
}
}
}
class Chef extends Thread
{
private Restaurant restaurant;
private Waitperson waitperson;
public Chef( Restaurant rest , Waitperson waitperson )
{
super( );
restaurant = rest;
this.waitperson = waitperson;
start( );
}
public void run( )
{
while( true )
{
if( restaurant.order == null )
{
restaurant.order = new Order( );
System.out.println("Order up!!");
synchronized( waitperson )
{
waitperson.notify();
}
}
try
{
sleep( 100 );
}
catch( java.lang.InterruptedException ex )
{
throw new RuntimeException( );
}
}
}
}
public class Restaurant
{
Order order;
public static void main( java.lang.String [] args )
{
Restaurant restaurant = new Restaurant( );
Waitperson waitperson = new Waitperson( restaurant );
Chef chef = new Chef( restaurant, waitperson );
}
}