Glue many non-stick words more not sweet, directly on the code:
Producer Class:
/*** Created by 51304 on 2016/2/28.*/ Public classP {PrivateString Lock; PublicP (String lock) { This. Lock =lock; } Public voidSetValue () {Try{ synchronized( This. Lock) { if(! ValueObject.value.equals ("") ) {lock.wait (); } String Value= System.currenttimemillis () + "_" +System.nanotime (); System.out.println ("Set value is" +value); Valueobject.value=value; Lock.notify (); } } Catch(interruptedexception e) {e.printstacktrace (); } }}
Consumer Category:
ImportCom.sun.org.apache.xpath.internal.SourceTree;/*** Created by 51304 on 2016/2/28.*/ Public classC {PrivateString Lock; PublicC (String lock) { This. Lock =Block; } Public voidGetValue () {Try{ synchronized( This. Lock) { if(ValueObject.value.equals ("")){ This. lock.wait (); } System.out.println ("Get value is" +valueobject.value); Valueobject.value= ""; This. Lock.notify (); } } Catch(interruptedexception e) {e.printstacktrace (); } }}
Objects that store values:
/***/Publicclass valueobject {publicstatic String value = "";}
Producer Threads:
/***/Publicclassextends Thread {private p p; Public THREADP (p p) { this. P= p; } @Override publicvoid run () { while (true ) { p.setvalue (); }}}
Consumer Threads:
/***/Publicclassextends Thread {private c C; Public THREADC (c c) { this. C= c; } @Override publicvoid run () { while (true ) { c.getvalue (); }}}
Main method:
/*** Created by 51304 on 2016/2/28.*/ Public classTestmain { Public Static voidMain (string[] args) {String lock=NewString (""); P P=NewP (lock); C C=NewC (lock); THREADP THREADP=NewTHREADP (P); THREADC THREADC=NewTHREADC (c); Threadp.start (); Threadc.start (); }}
Run:
Think: If multi-producer and multi-consumer programs work correctly?
The answer is: The program will appear in suspended animation, that is, all threads are stuck in the waiting state. This behavior occurs because the Notify () notification thread in multi-producer mode is a producer (random when the thread is selected, but only one is notified), and the same is true for consumers. Of course the solution is obviously using notifyall ().
Java Producer/consumer model implementation--one producer, one consumer (operational value)