classClerk {Private intProducts ; Private intMaximum//Maximum storage capacity PublicClerk (intmaxmum) { This. Maximum =Maxmum; } Public synchronized voidaddproduct () {if(Products >=maximum) { Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } Else{ Products++; System.out.println (Thread.CurrentThread (). GetName ()+ "Arrival" + Products + "product"); Notifyall (); } } Public synchronized voidsaleproduct () {if(Products > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Buy the first" + Products + "product"); Products--; Notifyall (); } Else { Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } }}classProducerImplementsrunnable{PrivateClerk Clerk; PublicProducer (Clerk clerk) { This. Clerk =clerk; } Public voidrun () { while(true) {clerk.addproduct (); Try{Thread.CurrentThread (). Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } } }}classConsumerImplementsRunnable {PrivateClerk Clerk; PublicConsumer (Clerk clerk) { This. Clerk =clerk; } Public voidrun () { while(true) {clerk.saleproduct (); Try{Thread.CurrentThread (). Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } } }}/*** Created by Bruce on 2018/7/22.*/ Public classProducerandconsumer { Public Static voidMain (string[] args) {Clerk Clerk=NewClerk (20); Thread T1=NewThread (NewProducer (clerk)); Thread T2=NewThread (NewConsumer (clerk)); Thread T3=NewThread (NewConsumer (clerk)); Thread T4=NewThread (NewConsumer (clerk)); T1.setname (Producers); T2.setname ("Consumer 1"); T3.setname ("Consumer 2"); T4.setname ("Consumer 3"); T1.start (); T2.start (); T3.start (); T4.start (); }}
Multithreaded programming Practice--realizing producer and consumer model