/** 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 --; Policy ();} public synchronized void v () {while (count> = cnt_max) {try {wait ();} catch (Interrupt EdException e) {}} count ++; y () ;}} 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 ("produced"); 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 ("consumed"); 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 ("Enter the repository size"); try {size = Integer. parseInt (new BufferedReader (new InputStreamReader (System. in ))). readLine ();} catch (IOException e) {}; System. out. println ("Enter the total amount to be produced"); try {total = Integer. parseInt (new BufferedReader (new Inpu TStreamReader (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 ){};}}
Test results:
________________________________
Enter the warehouse size.
1
Enter the total quantity to be produced
5
Produced 0th
0th consumed
Produced 1st
1st consumed
Produced 2nd
2nd consumed
Produced 3rd
3rd consumed
Produced 4th
4th consumed
__________________________________
Enter the warehouse size.
2
Enter the total quantity to be produced
5
Produced 0th
Produced 1st
0th consumed
Produced 2nd
1st consumed
Produced 3rd
2nd consumed
Produced 4th
3rd consumed
4th consumed