Packagecn.tt; Public classProducerconsumer { Public Static voidMain (string[] args)throwsinterruptedexception {syncstack ss=NewSyncstack (); Producer P=NewProducer (ss); Consumer C=Newconsumer (SS); NewThread (P). Start (); Thread.Sleep (2000); NewThread (c). Start (); }}classWotou {intID; Wotou (intID) { This. ID =ID; } @Override PublicString toString () {return"Wotou [id=" + 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. Notify (); Arrwt[index]=wt; Index++; } Public synchronizedWotou Pop () { while(Index = = 0) { Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } This. Notify (); Index--; returnArrwt[index]; }}classProducerImplementsRunnable {syncstack ss=NULL; PublicProducer (Syncstack ss) { This. SS =SS; } @Override Public voidrun () { for(inti = 0; I < 20; i++) {Wotou wt=NewWotou (i); Ss.push (WT); System.out.println ("Producer.run ()" +wt); Try{Thread.Sleep (Long) (Math.random () *1000)); } Catch(interruptedexception e) {e.printstacktrace (); } } }}classConsumerImplementsRunnable {syncstack ss=NULL; PublicConsumer (Syncstack ss) { This. SS =SS; } @Override Public voidrun () { for(inti = 0; I < 20; i++) {Wotou wt=Ss.pop (); System.out.println ("Consumer.run () >>>>>>>>>>>>" +wt); Try{Thread.Sleep (Long) (Math.random () *1000)); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
Java Threading-producer consumer model