Import java. util. vector;
Class test {
Private vector <string> mcache = new vector <string> ();
Static class Consumer implements runnable {
Private test mtestref;
Consumer (test T ){
Mtestref = T;
}
Public void run (){
Try {
For (;;){
Synchronized (mtestref ){
If (mtestref. mcache. Size ()> 0 ){
String item = mtestref. mcache. Get (0 );
Mtestref. mcache. Remove (0 );
System. Out. println ("consume the item:" + item );
} Else {
Mtestref. Wait ();
}
}
}
}
Catch (interruptedexception ex ){
}
}
}
Static class producer implements runnable {
Private test mtestref;
Private string mproducerid;
Producer (string ID, test T ){
Mproducerid = ID;
Mtestref = T;
}
Public void run (){
Try {
Int I = 0;
While (++ I) <5 ){
Synchronized (mtestref ){
String item = mproducerid + "#" + I;
Mtestref. mcache. Add (item );
Mtestref. Policy ();
}
Thread. Sleep (1000 );
}
}
Catch (interruptedexception ex ){
}
}
}
Public static void main (string [] ARGs ){
Test test = new test ();
Thread consumer = new thread (new consumer (TEST ));
Thread producer1 = new thread (new producer ("p1", test ));
Thread producer2 = new thread (new producer ("p2", test ));
Producer1.start ();
Producer2.start ();
Consumer. Start ();
Try {
Thread. Sleep (15000 );
Producer1.interrupt ();
Producer2.interrupt ();
Consumer. Interrupt ();
Producer1.join ();
Producer2.join ();
Consumer. Join ();
}
Catch (exception e ){
System. Out. println ("exception:" + E. getmessage ());
}
}
}
Output is:
Consume the item: P1 #1
Consume the item: P2 #1
Consume the item: P1 #2
Consume the item: P2 #2
Consume the item: P1 #3
Consume the item: P2 #3
Consume the item: P1 #4
Consume the item: P2 #4