Multithreading in Java (vi)

Source: Internet
Author: User

Producer Consumers

1 classResource2 {3     PrivateString name;4     Private intCount = 1;5     Private BooleanFlag =false;6     7      Public synchronized voidset (String name)8     {9          while(flag)Ten             Try{ This. Wait ();}Catch(Exception e) {} One          This. Name = name+ "--" +count++; ASystem.out.println (Thread.CurrentThread (). GetName () + "... Producer ... "+ This. Name); -Flag =true; -          This. Notifyall (); the     } -      -      Public synchronized voidout () -     { +          while(!flag) -             Try{ This. Wait ();}Catch(Exception e) {} +System.out.println (Thread.CurrentThread (). GetName () + "... Consumer ... "+ This. Name); AFlag =false; at          This. Notifyall (); -     } - } -  - classProducerImplementsRunnable - { in     PrivateResource Res; -      to Producer (Resource res) +     { -          This. res =Res; the     } *      $      Public voidRun ()Panax Notoginseng     { -          while(true) the         { +Res.set ("+tt+"); A         } the     } + } -  $ classCustomerImplementsRunnable $ { -     PrivateResource Res; -      the Customer (Resource res) -     {Wuyi          This. res =Res; the     } -      Wu      Public voidRun () -     { About          while(true) $         { - res.out (); -         } -     } A } + classProducercustomerdemo the { -      Public Static voidMain (string[] args) $     { theResource r =NewResource (); the          theProducer Pro =NewProducer (r); theCustomer con =NewCustomer (r); -          inThread T1 =NewThread (pro); theThread t2 =NewThread (con); the          About T1.start (); the T2.start (); the     } the}
View Code

Multithreading in Java (vi)

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.