1 PackageCom.bjsxt.Thread.Demo;2 Public classProducerconsumer {3 /**4 * Producers and consumers5 * @paramargs6 */7 Public Static voidMain (string[] args) {//Simulating Threads8Syncstack SS =NewSyncstack ();9Producer p =NewProducer (ss);TenConsumer C =NewConsumer (ss); One NewThread (P). Start ();//Open Thread A NewThread (c). Start ();//Open Thread - } - } the - /** - * Woto class - */ + classWoto { - intID; +Woto (intID) { A This. ID =ID; at } - PublicString toString () { - return"Woto:" +ID; - } - } - in /** - * Box class (used to pack steamed bread) to * @authorWenfei + */ - classSyncstack { the intindex = 0; *woto[] ARRWT =NewWoto[6]; $ Panax Notoginseng Public synchronized voidpush (Woto wt) { - the while(Index = =arrwt.length) { + A Try { the This. Wait ();//tentative Current Object + -}Catch(interruptedexception e) { $ e.printstacktrace (); $ } - } - This. Notify ();//Wake up Current thread theArrwt[index] =wt; -index++;Wuyi } the - Public synchronizedWoto Pop () { Wu while(Index = = 0) { - About Try { $ This. Wait (); -}Catch(interruptedexception e) { - e.printstacktrace (); - } A } + This. Notify (); theindex--; - returnArrwt[index]; $ } the } the the /** the * Producer - * in * @authorWenfei the */ the classProducerImplementsRunnable { AboutSyncstack SS =NULL; the the Producer (Syncstack ss) { the This. SS =SS; + } - the @OverrideBayi Public voidrun () { the //production WT the for(inti = 0; I <= 100; i++) { -Woto wt =NewWoto (i); -Ss.push (WT);//put a head in the basket theSystem.out.println ("Produced--->" +wt); the Try { the //Thread.Sleep (+);//every production one sleep a second theThread.Sleep ((int) Math.random () * 1000); -}Catch(interruptedexception e) { the //TODO auto-generated Catch block the e.printstacktrace (); the }94 } the } the the }98 About /** - * Consumer101 * 102 * @authorWenfei103 */104 classConsumerImplementsRunnable { theSyncstack SS =NULL;106 107 Consumer (Syncstack ss) {108 This. SS =SS;109 } the 111 @Override the Public voidrun () {113 for(inti = 0; I <= 100; i++) { theWoto wt =Ss.pop (); theSystem.out.println ("Consumption of--->" +wt); the Try {117 //Thread.Sleep (+);//One sleep per second spent118Thread.Sleep ((int) Math.random () * 1000);//119}Catch(interruptedexception e) { - //TODO auto-generated Catch block121 e.printstacktrace ();122 }123 //System.out.println (WT);124 } the }126 127}
Java_thread producers and Consumers Demo