Java thread safety and synchronization code blocks

Source: Internet
Author: User

Because in the e-commerce website work reason, for the second kill, Flash purchase and other promotional forms are quite familiar. No outside the business to take out a certain amount of inventory to do so-called "loss of business", the purpose is to use limited inventory to attract unlimited traffic. However, I have encountered a system problem, resulting in the second kill goods oversold situation. Poor merchant in fact only provided 10 pairs of 9.9 yuan of children's shoes to do the second kill, but in an instant sold 1000 pairs!

Similar to the problem, in non-thread-safe program design is very common, we run a second kill program:

public class Salesthread implements Runnable {private int stock = ten;        public void Run () {      if (stock>0) {    try{    Integer processingtime = new Random (). Nextint (    ). System.out.println (Thread.CurrentThread (). GetName () + ": Order Processing ...");    Thread.Sleep (processingtime);    System.out.println (Thread.CurrentThread (). GetName () +     ": Trading success, stock allowance:" +--stock);      } catch (Interruptedexception e) {    e.printstacktrace ();}}}}    

public static void Main (string[] args) {salesthread thread = new Salesthread (), for (int i=0;i<30;i++) {New Thread (thread , "client-" +i+1). Start ();}}

We tried to use the stock>0 inside the thread class to limit the sales of 10 inventory, but the actual results were as follows ... Everyone has bought my second kill product! It's dead! Heart Rubber Cork Stoppling!

CLIENT-01: Order Processing ... client-11: In order Processing ... client-31: Order Processing ... client-21: Order Processing ... client-51: Order Processing ... client-41: Order Processing in ..... CLIENT-61: Order Processing ... client-71: In order Processing ... client-91: Order Processing ... client-81: Order Processing ... client-101: Order Processing ... client-111: Order Processing in ..... client-131: Order Processing ... client-121: In order Processing ... client-141: Order Processing ... client-151: Order Processing ... client-161: Order Processing ... client-171: Order Processing ... client-191: Order Processing ... client-181: Order Processing ... client-201: Order Processing ... client-111: trading success, Stock margin: 8client-71: Successful trading, Stock allowance: 9client-291: In order Processing ... client-261: Order Processing ... client-281: Order Processing ... client-271: Order Processing ... client-251: Order Processing ... client-241: Order Processing ... client-231: Order Processing ... client-221: Order Processing ... client-211: Order Processing ... client-41: successful trading, Stock margin: 7client-101: Trading success, Stock margin: 6client-51: Trading success, Stock margin: 5client-251: Trading success, Stock margin: 4client-291: Trading success, Inventory margin: 3client-171: Trading Success, Stock margin: 2client-271: Trading success, Stock margin: 1client-01: Trading success, Stock margin: 0client-121: Trading success, Stock margin: -1client-201: Trading success, Inventory margin: -2client-261: Trading success , Stock margin: -3client-281: Trading success, Stock margin: -4client-151: Trading success, Stock margin: -5client-131: Trading success, Stock margin: -6client-221: Trading Success, Stock margin: -7client-241: Trading success, Stock margin: -8client-61: Trading success, Stock margin: -9client-21: Trading success, inventory surplusVolume: -10client-161: Trading success, Stock margin: -11client-81: Trading success, Stock margin: -12client-191: Trading success, Stock margin: -13client-141: Successful trading, Stock margin: -14client-211: Trading success, Stock margin: -15client-11: Trading success, Stock margin: -16client-31: Trading success, Stock margin: -17client-231: Successful trading, Stock margin: -18client-181: Trading success, Stock margin: -19client-91: Trading success, stock margin: 20

Java provides us with a synchronized keyword, which we understand as a synchronous lock that, when manipulating data shared by multiple threads, places the action that must be secured into the scope of the SYNCHRONIZED keyword--the synchronization code block , to ensure that, at the same time, There is only one thread that operates on the shared data and modifies the Salesthread source code to the following form:

public class Salesthread implements Runnable {private int stock = ten;  Private Object lock = new Object ();    public void Run () {while      (stock>0) {    synchronized (lock) {    if (stock>0) {    try{    Integer Processingtime = new Random (). Nextint (+);    System.out.println (Thread.CurrentThread (). GetName () + ": Order Processing ...");    Thread.Sleep (processingtime);    System.out.println (Thread.CurrentThread (). GetName () +     ": Trading success, stock allowance:" +--stock);      } catch (Interruptedexception e) {    e.printstacktrace ();}}}}}    

The processing results are as follows:

CLIENT-1: Order Processing ... client-1: trading success, Stock margin: 9client-8: Order Processing ... client-8: Trading success, Inventory margin: 8client-30: Order Processing ... client-30: trading success, Stock margin: 7client-30: Order Processing ... client-30: Trading success, Inventory margin: 6client-29: Order Processing ... client-29: Trading success, Inventory margin: 5client-28: Order Processing ... CLIENT-28: Trading Success, Inventory margin: 4client-27: Order Processing ... client-27: Trading success, Inventory margin: 3client-25: Order Processing ... client-25: trading success, Stock margin: 2client-26: Order Processing ... client-26: trading success, Stock margin: 1client-24: Order Processing ... client-24: trading success, stock margin: 0

Java thread safety and synchronization code blocks

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.