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