Producer and consumer model
The producer and consumer modes are shown in.
Blog purpose: Use graphs to speak.
Sample Code:
Package com. huan; public class ProduceConsumer {public static void main (String [] args) {Middleware middleware = new Middleware (); new Thread (new Producer (middleware )). start (); new Thread (new Consumer (middleware )). start () ;}} class Producer implements Runnable {private Middleware middleware; public Producer (Middleware middleware) {this. middleware = middleware;} public void produce () throws Exception {while (true) {middleware. put () ;}@ Overridepublic void run () {try {produce ();} catch (Exception e) {e. printStackTrace () ;}} class Consumer implements Runnable {private Middleware middleware; public Consumer (Middleware middleware) {this. middleware = middleware;} public void consume () throws Exception {while (true) {middleware. get () ;}@ Overridepublic void run () {try {consume ();} catch (Exception e) {e. printStackTrace () ;}} class Middleware {private static final int MAX_SIZE = 10; private int [] storage = new int [MAX_SIZE]; private int index = 0; public synchronized void put () throws Exception {if (index = MAX_SIZE) {wait ();} storage [index] = index; System. out. println ("produced:" + index); index ++; Policy ();} public synchronized void get () throws Exception {if (index = 0) {wait () ;}index --; System. out. println ("consumed:" + storage [index]); Using Y ();}}
Code defect: when multiple consumers or multiple producers, the code of the above example needs to be improved.