Java Advanced-producer consumer issues

Source: Internet
Author: User

Multithreading is a very important application, this section describes the synchronization problem in multi-threading

 Public classThreaddemo { Public Static voidMain (string[] args) {Resource R=NewResource (); Producer P1=NewProducer (R); Consumer C1=NewConsumer (R); NewThread (p1). Start (); NewThread (p1). Start (); NewThread (C1). Start (); NewThread (C1). Start (); }}/*Resource Class*/classResource {PrivateString name; Private BooleanFlag =false;//Resource Presence Tag//Production Resources     Public synchronized voidset (String name) { while(flag) {Try {                 This. Wait (); } Catch(Exception e) {e.printstacktrace (); }        }         This. Name =name; System.out.println (Thread.CurrentThread (). GetName ()+ "creator" +name); Flag=true;  This. Notifyall (); }    //Consumer Resources     Public synchronized voidget () { while(!flag) {            Try {                 This. Wait (); } Catch(Exception e) {e.printstacktrace (); }} System.out.println (Thread.CurrentThread (). GetName ()+ "Consumer" +name); Flag=false;  This. Notifyall (); }}/*Producer Class*/classProducerImplementsRunnable {PrivateResource R;  PublicProducer (Resource r) { This. R =R; }     Public voidrun () { while(true) {R.set (Goods); }    }}/*Consumer class*/classConsumerImplementsRunnable {PrivateResource R;  PublicConsumer (Resource r) { This. R =R; }     Public voidrun () { while(true) {r.get (); }    }}

The above code enables synchronization and resolves a factory production problem that generates a single consumption.

Java Advanced-producer consumer issues

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.