/* *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個