Java code:
Import java. util. ArrayList;
Import java. util. List;
/**
* Producer consumer demo implemented through wait and consumer y
* User: zhangb
* Date: 12-12-1
* Time: PM
*/
Public class ProducerAndCustomerDemo {
Private static int capacity = 150;
Private static List <String> basket = new ArrayList <String> (capacity );
Public static void main (String [] args ){
// Multiple producers and consumers
Int producerSize = 2;
Thread [] ps = new Thread [producerSize];
For (int I = 0, step = 500; I <producerSize; I ++ ){
Ps [I] = new Thread (new Producer (I) * step, (I + 1) * step ), "Production --> thread --" + (I + 1 ));
Ps [I]. start ();
}
Int customerSize = 10;
Thread [] cs = new Thread [mermersize];
For (int I = 0; I <customerSize; I ++ ){
Cs [I] = new Thread (new Customer (), "Consumption Thread --" + (I + 1 ));
Cs [I]. start ();
}
// Wait until the production thread ends and interrupt the consumption thread
For (int I = 0; I <producerSize; I ++ ){
Try {www.2cto.com
Ps [I]. join ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
For (int I = 0; I <customerSize; I ++ ){
Cs [I]. interrupt ();
}
}
Static class Producer implements Runnable {
Private int start;
Private int end;
Producer (int start, int end ){
This. start = start;
This. end = end;
}
@ Override
Public void run (){
For (int I = start; I <end; I ++ ){
Synchronized (basket ){
Try {
While (basket. size () = capacity ){
Basket. wait ();
}
String p = "PRO" + I;
System. out. println (Thread. currentThread (). getName () + p );
Basket. add (p );
Basket. policyall ();
Thread. yield (); // give the execution right of the current Thread, which helps to see the effect of alternate Thread running
} Catch (InterruptedException e ){
E. printStackTrace ();
Break;
}
}
}
}
}
Static class Customer implements Runnable {
@ Override
Public void run (){
While (true ){
Synchronized (basket ){
Try {
While (basket. size () = 0 ){
Basket. wait ();
}
System. out. println (Thread. currentThread (). getName () + basket. remove (0 ));
Basket. policyall ();
} Catch (InterruptedException e ){
System. out. println (Thread. currentThread (). getName () + "quit ");
Break;
}
}
}
}
}
}