Java Concurrency Learning 13--using conditions in synchronous code

Source: Internet
Author: User

This article is a summary of the study of the article on the network, thank you for your selfless sharing.

In fact, it is very simple, we see the code to know that is God horse meaning.

Package Chapter2;import Java.util.date;import Java.util.linkedlist;import Java.util.list;public class EventStorage { private int maxsize;private list<date> storage;public eventstorage () {maxSize = 10;storage = new Linkedlist<date > ();} Public synchronized void set () {while (storage.size () = = MaxSize) {try {wait ()} catch (Interruptedexception e) { E.printstacktrace ();}} ((linkedlist<date>) storage). Offer (new Date ()); System.out.println ("Set:" +storage.size ()); Notifyall ();} Public synchronized void get () {while (Storage.size () ==0) {System.out.println ("--------------------------- Wait--------------------"); try {wait ();} catch (Interruptedexception e) {e.printstacktrace ()}} System.out.printf ("get:%d:%s", Storage.size (), ((linkedlist<date>) storage). Poll ()); Notifyall ();}}

Package Chapter2;public class Producer implements Runnable{private eventstorage storage;public Producer (eventstorage Storage) {this.storage = storage;} @Overridepublic void Run () {for (int i=0;i<100;i++) {Storage.set ()}}}

Package Chapter2;public class Consumer implements Runnable {private eventstorage storage;public Consumer (eventstorage Storage) {this.storage = storage;} @Overridepublic void Run () {for (int i=0;i<100;i++) {storage.get ()}}}

This is a simple solution to the problem of producers and consumers.

Java Concurrency Learning 13--using conditions in synchronous code

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.