import java.util.*;

public class Hotel5
{
	static Random r;
	static Semaphore roomsSem;
	static Semaphore mealsSem;
	
	public static void main(String argv[])
	{
		int noThreads = Integer.parseInt(argv[0]);
		Hotel5 h = new Hotel5();
		r = new Random();
		roomsSem = new Semaphore( 10 );
		mealsSem = new Semaphore( 20 );
		
		Person[] threadObjects = new Person[noThreads];
		Thread[] threads = new Thread[noThreads];

		for (int i=0; i<noThreads; i++)
		{
			threadObjects[i] = new Person(h);
		} //for

		for (int i=0; i<noThreads; i++)
		{
			threads[i] = new Thread( threadObjects[i] );
			threads[i].start();
		} //for
	} //main()
	
	public void visitRoom()
	{
		System.out.println("thread named "+Thread.currentThread().getName()+" entered room");
		try
		{
			Thread.sleep(r.nextInt(1000));
		} //try
		catch (InterruptedException ie)
		{
			System.out.println("An InterruptedException caught\n"+ie.getMessage());
			ie.printStackTrace();
			System.exit(1);
		} //catch()
		System.out.println("thread named "+Thread.currentThread().getName()+" left room");
	} //visitRoom()			

	public void eat()
	{
		System.out.println("thread named "+Thread.currentThread().getName()+" is eating");
		try
		{
			Thread.sleep(r.nextInt(1000));
		} //try
		catch (InterruptedException ie)
		{
			System.out.println("An InterruptedException caught\n"+ie.getMessage());
			ie.printStackTrace();
			System.exit(1);
		} //catch()
		System.out.println("thread named "+Thread.currentThread().getName()+" finished meal");
	} //visitRoom()			

} //class Hotel5
// --------------------------------------------------------
class Person implements Runnable
{
	Hotel5 h;
	public Person(Hotel5 h)
	{
		this.h = h;
	} //constructor
	public void run()
	{
		h.roomsSem.p();
		h.visitRoom();
		h.roomsSem.v();

		h.mealsSem.p();
		h.eat();
		h.mealsSem.v();

	} //run()
} //class Person	