/*thread production and consumption*/classSynstack {Private Char[] data =New Char[6]; Private intCNT = 0;//represents the number of valid elements in an array Public synchronized voidPushCharch) { while(CNT = =data.length) {Try { This. Wait (); } Catch(Exception e) {}} This. Notify (); DATA[CNT]=ch; ++CNT; System.out.printf ("The production line is producing%d products, the product is:%c\n", CNT, CH); } Public synchronized Charpop () {Charch; while(cnt = = 0) { Try { This. Wait (); } Catch(Exception e) {}} This. Notify (); CH= Data[cnt-1]; System.out.printf ("Consumer thread is consuming%d products, the product is:%c\n", CNT, CH); --CNT; returnch; } }classProducerImplementsrunnable{PrivateSynstack SS =NULL; PublicProducer (Synstack ss) { This. SS =SS; } Public voidRun ()//throws Exception { //push (' a '); //Error Charch; for(inti=0; i<20; ++i) {//try{//Thread.Sleep (+);// }//catch (Exception e) {// }CH= (Char) (' a ' +i); Ss.push (CH); } }}classConsumerImplementsrunnable{PrivateSynstack SS =NULL; PublicConsumer (Synstack ss) { This. SS =SS; } Public voidrun () { for(inti=0; i<20; ++i) {Try{Thread.Sleep (100); } Catch(Exception e) {}//System.out.printf ("%c\n", Ss.pop ());Ss.pop (); } }} Public classtestpc{ Public Static voidMain (string[] args) {synstack ss=NewSynstack (); Producer P=NewProducer (ss); Consumer C=NewConsumer (ss); Thread T1=NewThread (P); T1.start (); Thread T2=NewThread (c); T2.start (); }}
Thread---consumption production