Use Lock to implement producer and consumer problems

Source: Internet
Author: User

Previously written: synchronize to implement producer and consumer problems

Now we use Lock to implement it.

Basket B = Product p = Consumer c = Consumer c1 = ManTou (. id = "ManTou" + max = 6 character list <ManTou> manTous = Character List <ManTou> Lock lock = ReentrantLock (); Condition full = lock. newCondition (); Condition empty = lock. newCondition (); (max = System. out. println ("the basket is full and will be reproduced later... "} ManTou m = (manTous. size () = 0 System. out. println ("the basket is empty. Please try again later... "m =} Product. basket = (I = 0; I <40; I ++ ManTou m = System. out. println ("produced" + Thread. sleep () (Math. random () * 2000} Consumer. basket = (I = 0; I <20; I ++ Thread. sleep () (Math. random () * 2000} ManTou m = System. out. println ("consumed" +}

Appendix: differences between synchronize and Lock




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.