Java implements producers and consumers

Source: Internet
Author: User

Producer and consumer problem is the classic problem of the operating system, in the actual work also often used, the main difficulty is to coordinate the producers and consumers, because the number of producers and the number of consumers is uncertain, and producers of the speed of production and consumer consumption speed is not the same, but also to achieve the decoupling of producers and consumers, That is, producers do not know what consumers are, and consumers do not need to know which products are produced, and they only have sex with one trading platform.

This is a common problem in the real world, such as we go to the Apple Store to buy the iphone 6, we belong to the consumer, and the manufacturer of products produced in the Apple Store, if the world has only one Apple store, when the store does not have an iphone 6 o'clock, we only wait, and when the store tun a lot of goods, So that the store will not fit, Apple, for example, manufacturers to suspend production. Producers and consumers are traded through a cache repository.

Java has linkedblockingqueue, Arrayblockingqueue can be in the concurrency environment to implement blocking insertions and deletions, well suited as a bond between producers and consumers.

Producers:

/*** Producer *@authorJiqunpeng **/classProducerImplementsRunnable {linkedblockingqueue<Integer>buffer; //construct the producer, register the warehouseProducer (linkedblockingqueue<integer>buffer) {         This. Buffer =buffer; }    /*** Production of a product, when the warehouse is full, waiting for the warehouse open space and then into the warehouse *@paramE *@throwsinterruptedexception*/     Public voidProduce (Integer e)throwsinterruptedexception {buffer.put (e); } @Override Public voidRun () {random random=NewRandom (7); Try {             while(true) {//life is endless .Integer Product =Random.nextint (); System.out.println ( This+ "\tproduct:\t" +product);                Produce (product); TimeUnit.MILLISECONDS.sleep (Random.nextint (500));//a short break            }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Consumers

/*** Consumer *@authorJiqunpeng **/classConsumerImplementsRunnable {linkedblockingqueue<Integer>buffer; //Register WarehouseConsumer (linkedblockingqueue<integer>buffer) {         This. Buffer =buffer; }    /*** from the warehouse to take out the product consumption, when there is no product in the warehouse, will wait forever@return     * @throwsinterruptedexception*/     PublicInteger consume ()throwsinterruptedexception {Integer e=Buffer.take (); returne; } @Override Public voidRun () {random random=NewRandom (7); Try {             while(true) {//I have to eat all my lifeInteger Product =consume (); System.out.println ( This+ "\tconsume:\t" +product); TimeUnit.MILLISECONDS.sleep (Random.nextint (2000));//I have to sleep.            }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Scheduled run

 Public classProducerconsumer { Public Static voidMain (string[] args) {//Task SchedulerExecutorservice exec = Executors.newfixedthreadpool (10); //Warehouse        Finallinkedblockingqueue<integer> buffer =NewLinkedblockingqueue<> (5);  for(inti = 0; I < 2; i++) {            //Create a producerProducer p =NewProducer (buffer); //lead the producers to the workshop, forced to work all night and nightExec.execute (P); //The consumer was bornConsumer C =NewConsumer (buffer); //consumers spend all their livesExec.execute (c); } exec.execute (NewRunnable () {@Override Public voidrun () { while(true) {                    //Check the warehouse space regularlySystem.out.println ("Buffer:" +buffer.size ()); Try{TimeUnit.SECONDS.sleep (5); } Catch(interruptedexception e) {e.printstacktrace ();    }                }            }        }); }}

Simulation results:

[Email protected] Product:-1156638823[email protected] consume:-1156638823[email protected] Product:-1156638823[email protected] consume:-1156638823Buffer:0[email protected] Product:-1077308326[email protected] Product:-1077308326[email protected] Product:1495978761[email protected] Product:1495978761[email protected] consume:-1077308326[email protected] consume:-1077308326[email protected] Product:-441191359[email protected] Product:-441191359[email protected] Product:-1253369595[email protected] Product:-1253369595[email protected] Product:1511462400[email protected] consume:1495978761[email protected] consume:1495978761[email protected] Product:1511462400[email protected] Product:518557417

Of course we can define a thread-safe bounded blocking cache queue ourselves:

 Public classBoundedbuffer<e> {    Privateobject[] buffer; Final PrivateReentrantlock Lock; Final PrivateCondition Notempty; Final PrivateCondition Notfull; Private intcount; Private intPutindex; Private intTakeindex;  PublicBoundedbuffer (intsize) {Buffer=NewObject[size]; Lock=NewReentrantlock (); Notempty=lock.newcondition (); Notfull=lock.newcondition (); }     Public voidPut (e e)throwsinterruptedexception {lock.lock (); Try {             while(Count = =buffer.length) notfull.await (); Buffer[putindex]=e; if(++putindex = = buffer.length)//Loop ArrayPutindex = 0; Count++;        Notempty.signal (); } finally{lock.unlock (); }    }     PublicE Take ()throwsinterruptedexception {lock.lock (); System.out.println ("Take ()"); Try {             while(count = = 0) notempty.await (); @SuppressWarnings ("Unchecked") E Item=(E) Buffer[takeindex]; Count--; if(++takeindex = = buffer.length)//Loop ArrayTakeindex = 0;            Notfull.signal (); returnitem; } finally{lock.unlock (); }    }}

Java implements producers and consumers

Related Article

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.