www.pudn.com > b02251132.rar > b02251132.java


//package b02251132;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author :»ÆÔö²© b02251132
* @version 1.0
*/
import javax.swing.*;
import java.io.*;
import java.util.*;

public class b02251132
{
public static Semophore sem=new Semophore(1);
public static void main(String[] args)
{
WaitingRoom myWaitRoom=new WaitingRoom(3);//Three seats at all.
Barber myBarber=new Barber(myWaitRoom);
myWaitRoom.start();
myBarber.start();
while(true)
{
//Whether there is customer and barber is free
if(myWaitRoom.customers>0&amt;&amt;myBarber.status==1)
{
System.out.println("One customer wake up the barber.");
myBarber.status=0;//Reset the status,barber is working.
myBarber.resume();//Make the barber's thread continue.

}
}
}
}



//That is the Semophore.
class Semophore
{
private int value;
public Semophore(){
value=0;
}
public Semophore(int v){
value=v;
}
public synchronized void p(){
while(value<=0){
try{
wait();
}
catch (InterruptedException e){}
}
value--;
}
public synchronized void v(){
++value;
notify();
}
}


class Barber extends Thread
{
public int status=0;//Reset the barber's working status.
WaitingRoom room1;
public Barber(WaitingRoom room)
{
room1=room;
}
public void run()
{
while(true)
{
if(room1.customers>0)
{
b02251132.sem.p();
room1.customers--;//One customer begin to be servered by the barber.
System.out.println("Barber begin to serve a customer.");
System.out.println("There is "+(room1.seats-room1.customers)+" Seat(s)");
b02251132.sem.v();
try {
sleep(2000);//Now,the barber is working,it should be 2 seconds.
}
catch (InterruptedException e) {}
System.out.println("Barber finished a customer,the customer leaves.");
System.out.println("There is "+(room1.seats-room1.customers)+" Seat(s)");
}
else
{
status=1;//Set the barber's working status become free.
System.out.println("No more customers,so barber go to sleep.");
suspend();//Make the barber's thread pause.

}
}
}
}



class WaitingRoom extends Thread
{
public int seats;
public int customers;
public WaitingRoom(int n)
{
customers=0;
seats=n;
}
public void run()
{
while(true)
{
try
{
sleep(1000);//Time between two customers' coming time.(1 second)
}catch(InterruptedException e){}
if(customers<seats)//If there is free seats available.
{
b02251132.sem.p();
customers++;//A customer come and occupy the seat.
b02251132.sem.v();
{
System.out.println("One customer comes and sits in the waiting room.");
System.out.println("There is "+(seats-customers)+" Seat(s)");
}
}
else
{
System.out.println("One customer arrives, but no free seats, so he leaves.");
}
}
}
}