Java Multithreading for natural Synchronization (demo case included)

Source: Internet
Author: User

1. Prepare a producer class:

 Public classProducerextendsthread{PrivateString name; PrivateMarket Mkt; Static intcount;  PublicProducer (String name, Market mkt) {Super(name);  This. Mkt =Mkt; } @Override Public voidrun () { This. Name =Thread.CurrentThread (). GetName (); SYSTEM.OUT.PRINTLN (Name+ "started production! ");  for(inti = 0; I < 5; i++) {            Try{Thread.Sleep (Long) (2000*math.random ())); } Catch(interruptedexception e) {e.printstacktrace (); } Count++; String Goods= "Goods" +count;        Mkt.set (goods); } System.out.println (Name+ "Production finished! "); }}

2. Prepare a consumer class:

 Public classConsumerextendsthread{PrivateString name; PrivateMarket Mkt;  PublicConsumer (String name,market mkt) {Super(name);  This. Mkt =Mkt; } @Override Public voidrun () { This. Name =Thread.CurrentThread (). GetName (); SYSTEM.OUT.PRINTLN (Name+ "Start spending!" "); StringBuilder SB=NewStringBuilder ();  for(inti = 0; I < 10; i++) {            Try{Thread.Sleep (Long) (2000*math.random ())); } Catch(interruptedexception e) {e.printstacktrace (); } String ShoppingCart=Mkt.get (); Sb.append (ShoppingCart). Append (" | "); } System.out.println (Name+ "Consumer shopping completed, the purchase list is as follows:"); System.out.println ("\ T" +SB); }}

3. Prepare a shopping arcade class:

 Public classMarket {PrivateString Shelf; Private BooleanFlag;  Public synchronized voidset (String goods) {string name=Thread.CurrentThread (). GetName ();  while(flag) {Try{System.out.println (name+ "try to buy goods but the shelves are full, please wait for consumption!" ");  This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }        }         This. Shelf =goods;  This. Flag =true; SYSTEM.OUT.PRINTLN (Name+ "+goods+" has been put on the goods, can be consumed! ");  This. Notify (); }         Public synchronizedstring Get () {string name=Thread.CurrentThread (). GetName ();  while(!flag) {SYSTEM.OUT.PRINTLN (name+ "trying to shop, but shelves are empty, please wait for the goods!" "); Try {                 This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} String ShoppingCart=Shelf;  This. Shelf =NULL;  This. Flag =false; SYSTEM.OUT.PRINTLN (Name+ "purchased a" +shoppingcart+ "! ");  This. Notify (); returnShoppingCart; }}

4. Test class:

 Public class Start {    publicstaticvoid  main (string[] args) {        new Market ();         New Producer ("Worker 1", mkt);         New Producer ("Worker 2", mkt);         New Consumer ("Customer", mkt);        P2.start ();        C.start ();        P1.start ();    }}

Java Multithreading for natural Synchronization (demo case included)

Related Article

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.