In multithreaded development, one of the most classic models is the producer consumer model, they have a buffer, the buffer has the maximum limit, when the buffer is full
, the producer is unable to put the product into the buffer, of course, when the buffer is empty, the consumer can not take out the product, which
Related to the conditional judgment in multi-threading, Java in order to implement these functions, provides the wait and notify method, they can not meet the requirements of the thread when
Let the threads let out resources to wait, when there are resources and then notify them to continue to work, below we use the actual code to show how to use wait and
Notify to achieve the classic model of producer consumers.
The first is the implementation of the buffer, we use LinkedList to replace
Package Com.bird.concursey.charpet2;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.printsta Cktrace ();}} Storage.add (New Date ()); System.out.printf ("Set:%d", storage.size ()); Notifyall ();} Public synchronized void get () {while (storage.size () = = 0) {try {wait ()} catch (Interruptedexception e) {//TODO Auto-gen Erated catch Blocke.printstacktrace ();}} System.out.printf ("Get:%d:%s", Storage.size (), ((linkedlist<?>) storage). Poll ()); Notifyall ();}}
Then there are producers and consumers.
Package Com.bird.concursey.charpet2;public class Producer implements Runnable {private Eventstorage Storge;public Producer (Eventstorage storage) {This.storge = storage;} @Overridepublic void Run () {for (int i = 0; i <; i++) {Storge.set ();}}}
Package Com.bird.concursey.charpet2;public class Consumer implements Runnable {private Eventstorage Storage;public Consumer (Eventstorage storage) {this.storage = storage;} @Overridepublic void Run () {for (int i = 0; i <; i++) {Storage.get ();}} public static void Main (string[] args) {eventstorage storage = new Eventstorage (); Producer Producer = new Producer (storage); Thread thread1 = new Thread (producer); Consumer Consumer = new Consumer (storage); Thread thread2 = new Thread (consumer); Thread2.start (); Thread1.start ();}}
You can see that this is the use of the wait and Notifyall method to achieve the producer consumption method, the specific operation process you can read the code to the body
Yes, it's still very intuitive.
Java Multi-thread ~ ~ ~ Using wait and notify to implement producer consumer models