Java implements the example code of producer and consumer
This article mainly introduces the "java realization of producer and consumer example code". In daily operation, I believe that many people have doubts about the java realization of producer and consumer example code. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "java realizes the example code of producer and consumer". Next, please follow the editor to study!
If will only judge once, while while will always judge.
Always use notifyAll, not notify.
Public class MyContainer1 {final private LinkedList lists = new LinkedList (); final private int MAX = 10; / / at most 10 elements private int count = 0; / / how many public synchronized void put (T t) {while (lists.size () = = MAX) {/ / think about using while instead of if? Try {this.wait (); / / effective java} catch (InterruptedException e) {e.printStackTrace ();}} lists.add (t); + + count This.notifyAll (); / / notify the consumer thread to consume} public synchronized T get () {T t = null; while (lists.size () = = 0) {try {this.wait () / / effective java} catch (InterruptedException e) {e.printStackTrace ();}} t = lists.removeFirst (); count--; this.notifyAll () / / notify the producer to produce return t;} public static void main (String [] args) {MyContainer1 c = new MyContainer1 (); / / start the consumer thread for (int item0; I {for (int jig0; j)