Multithreaded programming Practice--realizing producer and consumer model

Source: Internet
Author: User

classClerk {Private intProducts ; Private intMaximum//Maximum storage capacity   PublicClerk (intmaxmum) {     This. Maximum =Maxmum; }   Public synchronized voidaddproduct () {if(Products >=maximum) {      Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); }    } Else{ Products++; System.out.println (Thread.CurrentThread (). GetName ()+ "Arrival" + Products + "product");    Notifyall (); }  }   Public synchronized voidsaleproduct () {if(Products > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Buy the first" + Products + "product"); Products--;    Notifyall (); } Else {      Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); }    }  }}classProducerImplementsrunnable{PrivateClerk Clerk;  PublicProducer (Clerk clerk) { This. Clerk =clerk; }   Public voidrun () { while(true) {clerk.addproduct (); Try{Thread.CurrentThread (). Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); }    }  }}classConsumerImplementsRunnable {PrivateClerk Clerk;  PublicConsumer (Clerk clerk) { This. Clerk =clerk; }   Public voidrun () { while(true) {clerk.saleproduct (); Try{Thread.CurrentThread (). Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); }    }  }}/*** Created by Bruce on 2018/7/22.*/ Public classProducerandconsumer { Public Static voidMain (string[] args) {Clerk Clerk=NewClerk (20); Thread T1=NewThread (NewProducer (clerk)); Thread T2=NewThread (NewConsumer (clerk)); Thread T3=NewThread (NewConsumer (clerk)); Thread T4=NewThread (NewConsumer (clerk)); T1.setname (Producers); T2.setname ("Consumer 1"); T3.setname ("Consumer 2"); T4.setname ("Consumer 3");    T1.start ();    T2.start ();    T3.start ();  T4.start (); }}

Multithreaded programming Practice--realizing producer and consumer model

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.