Scene description

There's a big Mall , There are several commodity distribution centers in a city , And there are several branches , This mall deals in a lot of goods , The usual operation is like this :

According to the sales situation of each branch , Deliver the goods to the branch store according to the demand ; And put it on the shelf to give way to the branch store , For customers to choose .

Customers choose what they need , Then go to the cashier and pay for the package ;

And then at some point in the day, the branch manager ( Managers, etc. ), Start counting current sales , And plan to order the distribution volume of each commodity from the commodity distribution center ;

Scene simulation

1. Shopping malls ;

public class StoreMart {
// The rest of the day in the mall
private static Map<String, Integer> goodsMap = new HashMap<String, Integer>();
private static Map<String, Integer> priceMap = new HashMap<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);
//...
} // Choose products
//pn Name of commodity
//num Purchase quantity
public synchronized void selGoods(String name,String pn, int num) {
int total = getNum(pn);
int remain = total - num;
goodsMap.put(pn, remain); // Save user cart information
} // New product data
public synchronized void putGoods(String pn, int num) {
int total = getNum(pn);
total = total + num;
goodsMap.put(pn, total);
} public static int getNum(String pn) {
int num = 0; if (goodsMap.containsKey(pn)) {
num = goodsMap.get(pn);
} return num;
} // Settlement
public void settleGoods(Map<String, Integer> goods) {
//....
}
}

User shopping :

public class UserShop implements Runnable {
private static StoreMart sm = new StoreMart();
private final String name;
private final Map<String, Integer> sgoods = new HashMap<String, Integer>(); public UserShop(String name) {
this.name = name;
} public void add(String pn, int num) {
sgoods.put(pn, num);
} public void run() {
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 block
e.printStackTrace();
}
}
sm.settleGoods(sgoods);
System.out.println(this.name + " After shopping ! ");
} public static void main(String[] args) {
UserShop u1 = new UserShop("NameA");
u1.add("ap",1);
u1.add("bp",2);
Thread t1 = new Thread(u1); UserShop u2 = new UserShop("NameB");
u1.add("ap",4);
u1.add("bp",5);
Thread t2 = new Thread(u2); t1.start();
t2.start();
}
}

The above simulation shows that the quantity of commodities is sufficient ;

Two clients were simulated Each bought Different quantities of goods ap, bp;

But if there are more users , If there are several customers who want to buy the same product all at once, a lot of quantity ; There's going to be a problem ;

Use wait(), notify()

modify Next StoreMart class :

// Choose products 
//pn Name of commodity
//num Purchase quantity
public synchronized void selGoods(String name,String pn, int num) {
int total = getNum(pn);
while (total < num) {
System.out.println(pn + " Not enough goods ");
this.wait();
}
int remain = total - num;
goodsMap.put(pn, total); // Save user cart information
} // New product data
public synchronized void putGoods(String pn, int num) {
int total = getNum(pn);
total = total + num;
goodsMap.put(pn, total);
this.notify();
}

stay UserShop Of run In the method , Add the statement of goods shortage replenishment :

public void run() {
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 block
e.printStackTrace();
}
} // Find out there's not enough
sm.putGoods("ap", 100);
sm.putGoods("bp", 200);
System.out.println(this.name + " After shopping ! ");
}

such When you're in the mall When the quantity of a commodity is insufficient ,NameA or NameB You have to wait , Is to wait() To waiting collection , Waiting to be  notify() Wake up ;

synchronized, wait, notify explain

1. wait;

1>. be used for Dangben When the thread cannot be set up , Relinquish the currently occupied lock ;

2>. wait Must be in synchronized In the code block ;

3>. wait yes Object Methods ;

4>. Generally, we have to deal with while loop in vivo ; It is used to judge whether the condition is satisfied ;

2. synchronized In general, in a multithreaded environment , Used for processing Occupy The problem of sharing resources ;

3. notify be used for Wake up the wait() The thread of ;

wait And sleep The difference between

wait Aiming at At present synchronized The lock of the block :

1>. synchronized If Identify a General class , The lock is for the present The object of lock ;

2>. synchronized If Identify a Static class , That machine lock It's the class lock of the class ;

3>. If it is synchronized (obj) , be lock by obj object ; Generally, this lock can be defined as 0 Of length byte Array , It's more economical ;

sleep It's about the present Thread;

sleep  It's usually executed on a regular basis ;

wait It needs competition , Whether it can be implemented , It depends on whether the lock is assigned to it this time , Whether this condition is satisfied or not ;

interrupt() Can stop sleep or wait The pause state of ; If the thread A To stop Threads B, Call Threads B Example of interrupt() Method , When Threads B be in wait(),sleep(),join() when , Will throw  InterruptedException abnormal , stay catch Block execution return , You can end the thread normally ;

Java Multithreading (Thread) Sync (synchronized) as well as wait, notify relevant [ introduces ] More articles about

  1. Java Multithreading 5:Synchronized Locking mechanism

    One . Preface In multithreading , Sometimes multiple threads access the variables of the same object concurrently , If we don't do the right synchronization , So the consequence is “ Dirty reading ”, In other words, the acquired data is actually modified . Two . introduce Synchronized ...

  2. Java Multithreaded programming ( Sync 、 Deadlock 、 Production, consumer issues )

    Java Multithreaded programming ( Sync . Deadlock . Production and consumption ): About thread synchronization and deadlock : The concept of thread synchronization : It refers to the resource processing and protection operation when several thread objects access resources in parallel : Thread deadlock concept : Two threads are waiting for each other to finish first , build ...

  3. java Multithreading series ( 5、 ... and )---synchronized ReentrantLock volatile Atomic Principle analysis

    java Multithreading series ( 5、 ... and )---synchronized ReentrantLock volatile Atomic Principle analysis Preface : If there is something wrong , I hope you can correct me. . Catalog know cpu. Core and thread java ...

  4. Java Multithreading 6:Synchronized Lock code block (this And any object )

    One .Synchronized(this) Lock code block With keywords synchronized In some cases, the modification method has disadvantages , If it takes a long time to execute this method , Threads 1 When executing this method , Threads 2 You have to wait . In this case ...

  5. Java Synchronization control record of multithreading

    Java Synchronization control record of multithreading One . Reentrant lock Reentry lock can completely replace synchronized keyword . stay JDK 1.5 Early versions , The performance of reentry lock is better than synchronized.JDK 1.6 Start , about sy ...

  6. Java Synchronization collection and concurrency collection of multithreading

    Java Synchronization collection and concurrency collection of multithreading Both synchronous and concurrent collections support thread safety , The main differences between them are performance and scalability , And how they achieve thread safety . Synchronize collection classes Hashtable Vector Same as ...

  7. Java Multi thread synchronization mechanism (synchronized)

    a section synchronized Before the code is executed by a thread , He needs permission to execute this code first , stay java Inside is to get the lock of a synchronization object ( An object has only one lock ):  If the lock of synchronization object is taken away by other threads at this time , He ( This ...

  8. Java A brief analysis of multithreading ——Synchronized( Synchronization lock )、Lock And thread pools

    Java Multithreading Java in , All runnable programs are composed of one or more processes . Processes are composed of multiple threads . The simplest process , Will include mian Threads and GC Threads . State of thread The thread state is illustrated by the following online image : In the picture , ...

  9. Java Multithreading 2 (Synchronized)

    Commonly used API method notes run() run() Methods are the methods we have to implement when we create threads , But in fact, this method is just a common method , Direct calls don't turn on threads . start() start() The purpose of the method is to make ...

Random recommendation

  1. apache-shiro introduction &lt; One &gt;

    Apache Shiro It is a powerful and flexible open source security framework ( Originally, I wanted to upload it to the Internet for you to download , However, in view of the fact that the domestic network disk will be closed at any time, the user data will be clear : So I offered another shiro Download link of Chinese document :http://downlo ...

  2. java Static internal class summary

    Inner class means to define another class inside an outer class . Inner class as a member of outer class , And attached to an external class . Internal classes can be static , You can use protected and private modification ( The external class can only use public And default package access ...

  3. js Of match Method

    How to call ? String object .match( The target string ); Return value ? If there is , Just return this string : otherwise , return null example Take a common example , Determine whether the image path contains a string .

  4. Spring Learning summary ( 5、 ... and )——Spring Integrate MyBatis(Maven+MySQL) One

    MyBatis-Spring Will help you to MyBatis The code is seamlessly integrated into Spring in . Use the classes in this library , Spring Will load the necessary MyBatis Factory class and session class . This library ...

  5. PyQt4 Control loses focus and gains focus

    #QListView Control multiple choice settings self.ui.listView.setSelectionMode(QAbstractItemView.ExtendedSelection) # initialization QListView ...

  6. Inside The C++ Object Model - 03

    object Lessons 1.C++ The extra burden of layout and access time in is caused by virtual Caused by the :virtual function.virtual base class. Or because of multiple inheritance . 2.C ...

  7. YTU 2989: Basic operation of sequence table ( The linear table )

    2989: Basic operation of sequence table ( The linear table ) The time limit : 1 Sec   Memory limit : 128 MB Submit : 1   solve : 1 Title Description Write a program , Realize various basic operations of sequence table ( Suppose that the element type of the order table is char), ...

  8. jQuery Generate full page floating overlay effect (overlay)

    Maybe in the process of development , You often need to generate a full page overlay by yourself , So that users can focus on a certain area designated by the developer , In the development tips here , We use very simple code to generate similar effects , as follows : $("#ov ...

  9. ( turn ) From the memory tube The reason is 、 Memory leak 、 Memory recovery discussion C++ memory management

    http://www.cr173.com/html/18898_all.html Memory management is C++ The most hateful question , It's also C++ The most controversial issue ,C++ Experts get better performance from it , Greater freedom ,C++ rookie ...

  10. Unsuccessful TCA Code

    %--brain mask with the brain tissue mask_name = 'C:\Users\Administrator\Desktop\workspace\preprocess ...