/*
*Author:Junyi Sun
*From:CCNU
*E-mail:fxsjy@yahoo.com.cn
*/
import java.io.*;
class Semaphore
{
private int count;
private int cnt_max;
public Semaphore(int cnt,int cntm){
count=cnt;
cnt_max=cntm;
}
public synchronized void p(){
while(count<=0){
try{
wait();
}
catch(InterruptedException e){
}
}
count--;
notify();
}
public synchronized void v(){
while(count>=cnt_max){
try{
wait();
}
catch(InterruptedException e){
}
}
count++;
notify();
}
}
class Producer extends Thread
{
private Semaphore full,empty,mux;
private int total;
Producer(Semaphore _full,Semaphore _empty,Semaphore _mux,int _total){
full=_full;
empty=_empty;
mux=_mux;
total=_total;
}
private void tell(int i){
System.out.print("生产了第");
System.out.print(i);
System.out.print("个/n");
}
public void run(){
int i;
for(i=0;i<total;){
empty.p();
mux.p();
tell(i);
mux.v();
i++;
full.v();
}
}
}
class Consumer extends Thread
{
private Semaphore full,empty,mux;
private int total;
Consumer(Semaphore _full,Semaphore _empty,Semaphore _mux,int _total){
full=_full;
empty=_empty;
mux=_mux;
total=_total;
}
private void tell(int i){
System.out.print("消费了第");
System.out.print(i);
System.out.print("个/n");
}
public void run() {
int i;
for(i=0;i<total;){
full.p();
mux.p();
tell(i);
mux.v();
i++;
empty.v();
}
}
}
class IPC
{
public static void main(String args[]){
Semaphore full,empty,mux;
int size=0,total=0;
System.out.println("请输入仓库的大小");
try{
size=Integer.parseInt((new BufferedReader(new InputStreamReader(System.in))).readLine());
}catch(IOException e){
};
System.out.println("请输入要生产的总量");
try{
total=Integer.parseInt((new BufferedReader(new InputStreamReader(System.in))).readLine());
}catch(IOException e){
};
full=new Semaphore(0,size);
empty=new Semaphore(size,size);
mux=new Semaphore(1,1);
Producer producer=new Producer(full,empty,mux,total);
Consumer consumer=new Consumer(full,empty,mux,total);
producer.start();
while(!producer.isAlive());
consumer.start();
try{
System.in.read();
}
catch(IOException e){};
}
}
测试效果:
________________________________
请输入仓库的大小
1
请输入要生产的总量
5
生产了第0个
消费了第0个
生产了第1个
消费了第1个
生产了第2个
消费了第2个
生产了第3个
消费了第3个
生产了第4个
消费了第4个
__________________________________
请输入仓库的大小
2
请输入要生产的总量
5
生产了第0个
生产了第1个
消费了第0个
生产了第2个
消费了第1个
生产了第3个
消费了第2个
生产了第4个
消费了第3个
消费了第4个