Java Threading-Consumer & producer

Source: Internet
Author: User
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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.