Just when someone asks, write down the code directly.
Background: There is a warehouse to store goods, there are producers and consumers, design a can be implemented concurrently.
Design ideas: Design a warehouse class in which the maximum capacity limit and current count are saved, and the class contains methods for production and consumption, all of which are synchronized.
Specific code:
PackageCom.test.tiny; Public classStore {Private Final intmax_size;//Maximum Private intCount//Current PublicStore (intN) {max_size=N; Count= 0; } Public synchronized voidAdd () { while(Count >=max_size) {System.out.println ("It's full."); Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} Count++; System.out.println (Thread.CurrentThread (). toString ()+ "Put:" +count); This. Notifyall (); } Public synchronized voidRemove () { while(Count <= 0) {System.out.println ("It's empty."); Try { This. Wait (); }Catch(Exception e) {e.printstacktrace (); }} System.out.println (Thread.CurrentThread (). toString ()+ "Get:" +count); Count--; This. Notifyall (); } Public Static voidMain (string[] args) {//TODO auto-generated Method StubStore s =NewStore (5); Thread Pro=NewProducer (s); Thread Con=NewConsumer (s); Thread Pro2=NewProducer (s); Thread Con2=NewConsumer (s); Pro.setname ("Producer 1"); Con.setname ("Consumer 1"); Pro2.setname ("Producer 2"); Con2.setname ("Consumer 2"); Pro.start (); Con.start (); Pro2.start (); Con2.start (); }}classProducerextendsThread {PrivateStore S; PublicProducer (Store s) { This. S =s; } Public voidrun () { while(true) {s.add (); Try{Thread.Sleep (1000);//for intuition, rest for 1 seconds}Catch(Exception e) {e.printstacktrace (); } } }}classConsumerextendsThread {PrivateStore S; PublicConsumer (Store s) { This. S =s; } Public voidrun () { while(true) {s.remove (); Try{Thread.Sleep (1500);//for a more intuitive rest for 0.5 seconds}Catch(interruptedexception e) {e.printstacktrace (); } } }}
[JAVA Multithreading] producer consumer instances