Java thread Communication-producer consumer issues

Source: Internet
Author: User

Thread communication example-producer consumer issues

This kind of problem describes a situation, assume that the warehouse can only store one product, the producer will produce the product into the warehouse, the consumer will take away the product of the warehouse. Assuming there is no product in the warehouse, the producer can put the product into the warehouse and have the product, stop the production and wait until the product in the warehouse is consumed and taken away. . If the product is placed in the warehouse, the consumer can take the product away from consumption, otherwise stop spending and wait until the product is placed in the warehouse again. Obviously, this is a synchronization issue, where producers and consumers share the same resources, and producers and consumers rely on each other to move forward in terms of each other. Java provides 3 methods to solve the communication problems between the threads, Wait () notify () and Notifyall ()
* (1) Call the Wait () method: the thread that called the method frees the shared resource's lock, then exits from the running state, enters the wait queue, and wakes up again
* (2) call the Notify () method: Wakes the first thread in the wait queue to wait for the same shared resource, and causes the thread to exit wait and enter the ready state
* (3) Call the Notifyall () method: Causes all threads that are waiting on the same shared resource in the queue to exit from the wait state, at which point the highest priority thread executes first

1  PackageCom.iotek.productconsumerdemo;2 3 Importjava.util.LinkedList;4 5  Public classProductorconsumerdemo {6 7     /**8 * Thread Communication-wait () notify () Notifyall ( )9 * In real-world applications, it is often necessary to allow that multiple threads to access shared resources in order of I, such as classic producer consumer issues:Ten * This type of problem describes a situation where a product can only be stored in a warehouse where the producer puts the product into the warehouse, and the consumer One * The products in the warehouse take away the consumption, if there is no product in the warehouse, the producer can put the product into the warehouse, otherwise stop production and wait until A * The product in the warehouse is consumed so far, if there is a product in the warehouse, then the consumer can take away the product to consume, otherwise stop consuming and wait, - * Until the product is placed in the warehouse again -      * @paramargs the      *  -      */ -      Public Static voidMain (string[] args) { -Basket Basket =Newbasket (); +Productor Productor =NewProductor (basket);//Create a Producer object -Consumer Consumer =NewConsumer (basket);//Create consumer Objects +Productor.start ();//Producers start production AConsumer.start ();//consumers begin to consume at     } -  - } -  - classConsumerextendsThread { -     PrivateBasket Basket =NULL; in  -      PublicConsumer (Basket basket) { to          This. Basket =Basket; +     } - @Override the      Public voidrun () { *Basket.popapple ();//consumers take apples from baskets $     }Panax Notoginseng } -  the classProductorextendsThread { +     PrivateBasket Basket =NULL; A  the      PublicProductor (Basket basket) { +          This. Basket =Basket; -     } $  $ @Override -      Public voidrun () { -Basket.pushapple ();//The producers put apples in the basket the     } - }Wuyi  the //Basket class for storing apples (requires a container to store, frequent access, with LinkedList), or to fetch apples - classBasket { Wu     PrivateLinkedlist<apple> Basket =NewLinkedlist<apple>(); -  About     //four-wheel apple $      Public synchronized voidpushapple () { -         //synchronized lock, Apple can not be taken when putting apples -          for(inti = 0; I < 20; i++) { -Apple Apple =NewApple (i); A push (apple); +         } the     } -  $     //take 4 rounds of apples the      Public synchronized voidpopapple () { the          for(inti = 0; I < 20; i++) { the pop (); the         } -     } in  the     //put apples in the basket This method is not used externally, so it is set to private the     /* Public*/Private voidpush (apple apple) { About         //If there are already 5 apples in the basket, wait and inform the consumer to consume the         if(basket.size () = = 5) { the             Try { theWait ();//wait, and release the lock for the current object +                 /*Attention!!! Calling the Wait () method to enter the waiting thread must be called by another thread to invoke the Notify () or Notifyall () method to wake the*/ -}Catch(interruptedexception e) { the e.printstacktrace ();Bayi             } the         } the         //if it's not over 5 apples, keep the apples on. -         Try { -Thread.Sleep (500);//put an apple every 500ms the             //sleep () automatically starts the thread after the current thread is set to sleep every time the}Catch(interruptedexception e) { the e.printstacktrace (); the         } -Basket.addfirst (Apple);//Store Apples theSystem.out.println ("Store:" +apple.tostring ()); theNotify ();//inform consumers to consume the     }94  the     //take apples from the basket the     /* Public*/Private voidpop () { the         //when the number of apples in the basket is 0, wait and inform the producer to produce98         if(basket.size () = = 0) { About             Try { - wait ();101}Catch(interruptedexception e) {102 e.printstacktrace ();103             }104         } the         //if the apples in the basket are not 0, then consume, every interval, consume an apple106         Try {107Thread.Sleep (500);108}Catch(interruptedexception e) {109 e.printstacktrace (); the         }111Apple Apple = Basket.removefirst ();//Take out an apple theSystem.out.println ("Eat:" +apple.tostring ());113Notify ();//inform producers to produce the  the     } the }117 118 //Apple class119 classApple { -     Private intID;121 122      PublicApple (intID) {123          This. ID =ID;124     } the 126 @Override127      PublicString toString () { -         return"Apple:" + (ID + 1);129     } the}

Java thread Communication-producer consumer issues

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.