Horse soldier Teacher's producer consumer model, I feel understand the producer consumer model, basically understand half multi-threading.
Public classProducerconsumer { Public Static voidMain (string[] args) {syncstack ss=NewSyncstack (); Producer P=NewProducer (ss); Consumer C=NewConsumer (ss); NewThread (P). Start (); NewThread (c). Start (); }}classWotou {intID; Wotou (intID) { This. ID =ID; } PublicString toString () {return"Wotou:" +ID; }}classSyncstack {intindex = 0; Wotou[] ARRWT=NewWotou[6]; Public synchronized voidpush (Wotou wt) { while(Index = =arrwt.length) {Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } This. Notifyall (); Arrwt[index]=wt; Index++; } Public synchronizedWotou Pop () { while(Index = = 0) { Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } This. Notifyall (); Index--; returnArrwt[index]; }}classProducerImplementsRunnable {syncstack ss=NULL; Producer (Syncstack ss) { This. SS =SS; } Public voidrun () { for(inti = 0; I < 20; i++) {Wotou wt=NewWotou (i); Ss.push (WT); System.out.println ("Produced:" +wt); Try{Thread.Sleep (int) (Math.random () * 200)); } Catch(interruptedexception e) {e.printstacktrace (); } } }}classConsumerImplementsRunnable {syncstack ss=NULL; Consumer (Syncstack ss) { This. SS =SS; } Public voidrun () { for(inti = 0; I < 20; i++) {Wotou wt=Ss.pop (); System.out.println ("Consumed:" +wt); Try{Thread.Sleep (int) (Math.random () * 1000)); } Catch(interruptedexception e) {e.printstacktrace (); } } }}