Thread---consumption production

Source: Internet
Author: User

/*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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.