import java.util.concurrent.Semaphore;public class 理发师问题
{
static int count=0;
static Semaphore mutex=new Semaphore(1);
static Semaphore chair=new Semaphore(5);
static Semaphore empty=new Semaphore(1);
static Semaphore full=new Semaphore(0);
static Semaphore cut=new Semaphore(0);
public static void main(String args[])
{
new Thread(new barber()).start();
new Thread(new customer()).start();
}
static class barber implements Runnable
{
public void run()
{
while(true)
{
try
{
full.acquire();
     System.out.println("我是理发师,替顾客理发");
     cut.release();
     //empty.release();
}
catch(InterruptedException e)
{
System.out.println("出现异常。");
}
}
}
}
static class customer implements Runnable
{
public void run()
{
try
{
mutex.acquire();
if(count>5)
{
mutex.release();
System.out.println("一个顾客因人太多而离开理发店");
}
else
{
     count=count+1;
     mutex.release();
     if(count>1)
     {
     chair.acquire();
     System.out.println("一个顾客在等候椅上等");
     empty.acquire();
     System.out.println("一个顾客从等候椅上起来");
     chair.release();
}
else    //count==1
{
empty.acquire();
   System.out.println("一个顾客在理发椅上就座");
     full.release();
     cut.acquire();
     //System.out.println("顾客理发");
     empty.release();
     mutex.acquire();
     count=count-1;
     mutex.release();
     System.out.println("一个顾客离开理发店");
}
}
}
catch(InterruptedException e)
{
System.out.println("出现异常。");
}
}
}
}