In the process, the producer is the thread of production data, and the consumer is the thread of consumption data. In multithreaded development, producers have to wait for the consumer to continue producing data if the producer is processing fast and the consumer processing is slow. Similarly, consumers must wait for producers if their processing power is greater than that of producers. To solve this problem, the producer and consumer models were introduced. A simple producer consumer model is implemented below:
1. A consumer, a producer, cycles the production of consumption
PackageSoarhu;Importjava.util.ArrayList;Importjava.util.List;classservice{Private FinalObject Lock; Privatelist<string> list =NewArraylist<>(); PublicService (Object lock) { This. Lock =lock; } voidWaiting () {synchronized(lock) {Try { while(List.size () ==0) {lock.wait (); } String Value= List.remove (0); System.out.println ("Consume:" +value); Lock.notifyall (); } Catch(interruptedexception e) {e.printstacktrace (); } } } voidnotifying () {synchronized(lock) {Try { while(List.size ()!=0) {lock.wait (); } String Value=system.currenttimemillis () + ""; List.add (value); System.out.println ("Produce:" +value); Lock.notifyall (); } Catch(interruptedexception e) {e.printstacktrace (); } } }} Public classTest { Public Static voidMain (string[] args)throwsinterruptedexception {Object o=NewObject (); Service Service=NewService (o); for(inti = 0; I < 1; i++) {//the number here is 1. NewThread () {@Override Public voidrun () { while(true) {service.notifying (); }}}.start (); } thread.sleep (1000); for(inti = 0; I < 1; i++) {//at this point the number is changed to 1 NewThread () {@Override Public voidrun () { while(true) {service.waiting (); }}}.start (); } }}
Output results
produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866Produce:1492495274866Consume:1492495274866.................................
Basic Overview of Java Multithreading (vi)--Simple producer consumer model