Java Multithreading (thread) synchronization (synchronized) and wait, notify related [example introduction]

Source: Internet
Author: User

Scenario Description

There is a big shopping mall, there are several goods distribution centers in a certain city, and there are several branches, this mall operates a lot of goods, usually operating situation is this:

According to each branch of the merchandise sales situation, to the branch distribution of the corresponding demand for goods, and shelves to the location of the position for customers to buy.

Customers choose the goods they need, then pay the money to the cashier to pack;

Then to a certain time of the day the branch manager (managers, etc.), began to count the current sales situation, and plan to the Commodity Distribution center to order the distribution of goods;

Scene simulation

1. Shopping malls category;

 Public classStoremart {//The amount of merchandise left on the market this day    Private Staticmap<string, integer> goodsmap =NewHashmap<string, integer>(); Private Staticmap<string, integer> pricemap =NewHashmap<string, integer>(); Static{goodsmap.put ("AP", 1000); Goodsmap.put ("BP", 500); Goodsmap.put ("CP", 2000); Pricemap.put ("AP", 20); Pricemap.put ("BP", 50); Pricemap.put ("CP", 30); //...    }        //Select a product//PN Product Name//num Purchase Quantity     Public synchronized voidSelgoods (String name,string pn,intnum) {        intTotal =getnum (PN); intremain = Total-num;                Goodsmap.put (pn, remain); //Save User Shopping cart information    }        //New Product Data     Public synchronized voidPutgoods (String pn,intnum) {        intTotal =getnum (PN); Total= Total +num;    Goodsmap.put (PN, total); }         Public Static intgetnum (String pn) {intnum = 0; if(Goodsmap.containskey (PN)) {num=goodsmap.get (PN); }                returnnum; }        //settlement     Public voidSettlegoods (map<string, integer>goods) {        //....    }}

User Shopping Category:

 Public classUsershopImplementsRunnable {Private StaticStoremart SM =NewStoremart (); Private FinalString name; Private Finalmap<string, integer> sgoods =NewHashmap<string, integer>();  Publicusershop (String name) { This. Name =name; }         Public voidAdd (String pn,intnum)    {sgoods.put (pn, num); }         Public voidrun () { for(Map.entry<string, integer>Entry:sgoods.entrySet ())                    {Sm.selgoods (Entry.getkey (), Entry.getvalue ()); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }} sm.settlegoods (Sgoods); System.out.println ( This. Name + "Shopping complete!"); }         Public Static voidMain (string[] args) {usershop u1=NewUsershop ("Namea"); U1.add ("AP", 1); U1.add ("BP", 2); Thread T1=NewThread (U1); Usershop U2=NewUsershop ("Nameb"); U1.add ("AP", 4); U1.add ("BP", 5); Thread T2=NewThread (U2);        T1.start ();    T2.start (); }}

The above is a case of sufficient quantity of goods;

Two customers have been touched to buy a different number of commodities AP, BP;

But if the user more up, if there are a few customers to buy a lot of the same product quantity;

Use Wait (), notify ()

Modify the following Storemart class:

//Select a product//PN Product Name//num Purchase Quantity Public synchronized voidSelgoods (String name,string pn,intnum) {    intTotal =getnum (PN);  while(Total <num) {SYSTEM.OUT.PRINTLN (pn+ "Insufficient quantity of goods");  This. Wait (); }    intremain = Total-num;            Goodsmap.put (PN, total); //Save User Shopping cart information}    //New Product Data Public synchronized voidPutgoods (String pn,intnum) {    intTotal =getnum (PN); Total= Total +num;    Goodsmap.put (PN, total);  This. Notify ();}

In the Usershop Run method, add the statement that the item is not under replenishment:

 Public voidrun () { for(Map.entry<string, integer>Entry:sgoods.entrySet ())                {Sm.selgoods (Entry.getkey (), Entry.getvalue ()); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }                //found the goods are not enoughSm.putgoods ("AP", 100); Sm.putgoods ("BP", 200); System.out.println ( This. Name + "Shopping complete!");}

In this way, when a commodity in the mall is insufficient, NAMEA or NAMEB will have to wait, that is, wait for the collection, waiting to be notify () to wake up;

Synchronized, wait, notify description

1. Wait;

1>. Used to discard the currently occupied lock when this thread is not valid;

2>. Wait must be within the code block where the synchronized resides;

3>. Wait is the method of Object;

4>. Generally to deal with while loop body; Used to re-determine whether the condition is satisfied;

2. Synchronized general end of multi-threaded environment, for the use of shared resources to deal with the problem;

3. Notify is used to wake the wait () thread;

The difference between wait and sleep

Wait is for the machine lock of the block where the current synchronized is located:

1>. Synchronized if an ordinary class is identified, the lock is the lock of the current object;

2>. Synchronized if a static class is identified, that machine lock is the class lock of the class in which it is located;

3>. If synchronized (obj), the lock is an obj object; Generally this lock can be defined as a 0-length byte array, which is relatively economical;

The sleep pin is the current Thread;

Sleep is usually performed on a timed basis;

Wait is the need to compete, can execute, depends on whether the lock is assigned to it, the condition is satisfied;

Interrupt () can abort the suspend state of sleep or wait, and if thread A aborts thread B, it calls the interrupt () method of the thread B instance, and when thread B is in wait (), sleep (), join (), it throws Interr Uptedexception exception, in the Catch block execution return, the normal end of the thread;

Java Multithreading (thread) synchronization (synchronized) and wait, notify related [example introduction]

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.