Multi-threaded ticket selling problem

We simulate a scenario where multiple windows sell tickets at the same time.
The crux of the matter isTwo people cannot sell a ticket with the same number

Two keywords:
staticMethods or objects must be static
synchronizedThis is the key word of lock

The method with synchronized and static is calledclass level lock
The method with synchronized and no static is calledObject level lock

We can meet our needs in two ways:

class level lock

method one:

package com.Keafmd.day0102;

/**
 * Keafmd
 *
 * @ClassName: MultiThreadedTicketSelling01
 * @Description: Multi-threaded ticket selling class level lock (Method 1)
 * @author: The awesome Conan
 * @date: 2021-01-02 22:08
 */
public class MultiThreadedTicketSelling01 implements Runnable {

    private static int num = 10; // It must be static, otherwise the getTicket() below will not be accessible.
    private String name = "";


    public MultiThreadedTicketSelling01(String name) {
        this.name = name;
    }

    @Override
    public void run() {

        while (num > 0) {
            System.out.println(name + "Selling tickets:" + getTicket());
            try {
                Thread.sleep(1000); //Delay, otherwise the effect will not be seen too fast
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //Class-level lock (Method 1)
    private synchronized static int getTicket() {
        return num--;
    }


    public static void main(String[] args) {

        New Thread (new MultiThreadedTicketSelling01 (" conan ")). The start ();
        New Thread (new MultiThreadedTicketSelling01 (" xiao LAN ")). The start ();
    }


}

operation result:

Xiaolan is selling tickets: 10
Conan is selling tickets: 9
Conan is selling tickets: 7
Xiaolan is selling tickets: 8
Xiaolan is selling tickets: 6
Conan is selling tickets: 5
Conan is selling tickets: 4
Xiaolan is selling tickets: 3
Conan is selling tickets: 2
Xiaolan is selling tickets: 1

Process finished with exit code 0

Object level lock

Method Two:

package com.Keafmd.day0102;

/**
 * Keafmd
 *
 * @ClassName: MultiThreadedTicketSelling02
 * @Description: Multi-threaded ticket selling object level lock (method 2)
 * @author: The awesome Conan
 * @date: 2021-01-02 22:25
 */
public class MultiThreadedTicketSelling02 implements Runnable{

    private static int num=10; // It must be static, otherwise num will not be locked and the same ticket will be sold twice.
    private  String name ="";
    private static Object obj = new Object(); // It must be static, otherwise the object cannot be locked, and the tickets sold by the current object cannot be locked.

    public MultiThreadedTicketSelling02(String name) {
        this.name = name;
    }

    @Override
    public void run() {

        while(num>0){
            System.out.println(name+"Selling tickets:"+getTicket());
            try {
                Thread.sleep(1000); //Delay, otherwise the effect will not be seen too fast
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    //Object level lock (method 2)
    private  int getTicket(){
        synchronized(obj){
            return num--;
        }

    }


    public static void main(String[] args) {

        New Thread (new MultiThreadedTicketSelling02 (" conan ")). The start ();
        New Thread (new MultiThreadedTicketSelling02 (" xiao LAN ")). The start ();
    }



}

operation result:

Conan is selling tickets: 10
Xiaolan is selling tickets: 9
Conan is selling tickets: 8
Xiaolan is selling tickets: 7
Xiaolan is selling tickets: 6
Conan is selling tickets: 5
Xiaolan is selling tickets: 3
Conan is selling tickets: 4
Xiaolan is selling tickets: 1
Conan is selling tickets: 2

Process finished with exit code 0

In the running results, it is possible that ticket No. 3 is sold before ticket No. 4. This is a normal situation. We can understand this situation as Conan has (4, 3, 2, 1) left when selling tickets, so Conan plans to give the customer ticket No. 4. At this time, the ticket No. 4 has been sold in the system, but the transaction with the customer has not yet been completed. At this time, Xiaolan is selling tickets at another window, and there are still (3, 2, 1) So Xiaolan sells ticket No. 3, but Xiaolan trades with customers quickly, so Xiaolan will sell ticket No. 3 first,As long as you don’t sell an account twice, it’s normal.

If it was helpful to you after reading, thank you for your likes and support!
If you are on a computer, see the “One click three consecutive“Yes, click it [haha]

come on!

Work together!

Keafmd

—————Dividing line—————

For the first time, I would like to thank you all for your corrections in the comment area. Due to my fault, some words were not clearly stated at the beginning. Today, after seeing the comments from readers, I quickly improved them. Here I will also reply to all readers in the comment area. As for why static is used, I re-explained it in the comments. At the same time, due to my mistake, there was something wrong with the first class-level lock, which has been corrected. Thank you again for your corrections!

Related Posts

IDEA sets comments such as author and date for [class] and [method] (suitable for beginners)

[es]java uses three query usages in es from size, search after, scroll

Greedy algorithm introductory question set

Teach you dubbo custom load balancing strategy from scratch

mac pro M1 (ARM) installation: jdk|java|dynamically switch jdk version

Detailed explanation of @PostConstruct annotation

Java collections – the difference between HashMap and TreeMap

Flutter’s AES encryption (NoPadding filling method)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*