This is the 26th day of my participation in the More Text Challenge. For more details, see more text Challenge


Related articles

Java Multithreading summary: Java multithreading


1. Thread scheduling sequence

Premise: If there are three threads running in a process, who comes first?

  • Code implementation case:
/** * test thread execution order */
public class TestThreadSort implements Runnable{
    public static void main(String[] args) {
        // The benefit of using the implementation Runnable method is that it can be implemented multiple times
        TestThreadSort testThreadSort = new TestThreadSort();

        // Start thread 1
        new Thread(testThreadSort,"Ding Da").start();
        // Start thread 2
        new Thread(testThreadSort,"A big").start();
        // Start thread 3
        new Thread(testThreadSort,"B big").start();
    }

    @Override
    public void run(a) {
        Thread.currentthread ().getname () -- get the name of the currentThread
        for (int i=0; i<100; i++){ System.out.println(Thread.currentThread().getName()+"Look at the number."+i+"Book"); }}}Copy the code
  • The execution result is as follows:

  • Note:

    • When a Thread is started, new Thread(instantiated object, name) gives a name to the Thread being started.
    • Inside a Thread, you can use thread.currentThread ().getName() to get the name of the Thread itself.
  • Summary:

    • From the above code execution results, we can conclude that the execution of threads is not in the specified order. For example, I turn on threads 1, 2, and 3 in turn, but the actual execution results are not under our control, but are randomly scheduled by the CPU scheduler!

Second, the execution of the main thread

  • Code implementation Case

  • Theoretical result: wait for three people to finish reading, the teacher is the last to read.

  • The actual results are as follows:

  • Conclusion: The main thread (main() thread) executes first.

Concurrency of threads

Concurrency, in the operating system, refers to the time period when several programs are running on the same processor, but only one program is running on the processor at any one time point. —- above excerpt from Baidu Encyclopedia

3.1. The race between the tortoise and the hare

  • Before starting concurrency, let’s look at a fun example. The tortoise and the hare have a race.

  • Program implementation

    • The track two
    • The Turtle and the Hare
    • The length of the track
    • Historically, you need to rest the rabbits (because the rabbits lose)
    • Sleep (int) Thread sleep, in milliseconds
  • Code implementation case:

public class RunGame implements Runnable{

    Integer track = 100;// The length of the track
    String turtle = "The tortoise";
    String rabbit = "Rabbit";
    String winner = "";/ / the winner

    public static void main(String[] args) {
        RunGame runGame = new RunGame();

        // Start the rabbit race thread
        new Thread(runGame, runGame.rabbit).start();
        // Start the tortoise race thread
        new Thread(runGame, runGame.turtle).start();
    }

    @Override
    public void run(a) {
        // Use thread.currentThread ().getName() to get who the current contestant is
        String ballplayer = Thread.currentThread().getName();
        if (ballplayer.equals(rabbit)){
            // Simulate the speed at which a rabbit runs. The speed at which a rabbit runs is defined as two meters per second
            for (int i=0; i<=track; i+=2){
                System.out.println(rabbit+"Run away"+i+"米");
                // Because the rabbit is very proud, when the rabbit ran to 60 meters, he took a nap, so he lost the race
                if (i==50) {try {
                        Thread.sleep(200);
                    } catch(InterruptedException e) { e.printStackTrace(); }}if (i>=100){
                    winner = rabbit;
                    System.out.println(winner+"赢了!!!"); }}}else if (ballplayer.equals(turtle)){
            // Simulate the speed at which a tortoise runs. The speed at which a tortoise runs is defined as one meter per second
            for (int i=0; i<=track; i++){ System.out.println(turtle+"Run away"+i+"米");
                if (i>=100){
                    winner = turtle;
                    System.out.println(winner+"赢了!!!");
                }
            }
        }
    }
}

Copy the code
  • Execution Result:

  • When the rabbit ran to 50 meters, he became complacent and fell asleep. As a result, he lost the race.

  • Under normal circumstances, the rabbit will definitely win, remove the hibernation can, I do not put the code and results up, interested can try their own ~

3.2 cases of commodity snapping up

  • Concurrent scenarios:

    • Brush Monkey King lei Jun for sale mi 12, the first batch of goods only 100!! 100!!
    • After everyone knew the news, they came to buy Mi 12 at 12 o ‘clock, the number of 500 people!
    • Mobile phone, is certainly not enough ~
    • Let’s simulate a mobile phone rush
  • Code implementation case:

/** * Mobile phone buying cases */
public class PhoneSnapUp implements Runnable{

    private Integer inventory = 100;// Mobile phone inventory
    private Integer number = 500;// Number of buyers

    public static void main(String[] args) {
        PhoneSnapUp phoneSnapUp = new PhoneSnapUp();
        // Simulate 500 people snapping at the same time, i.e. 500 threads open at the same time
        for (int i=0; i<500; i++){new Thread(phoneSnapUp,"Ding Da"+i+"Number one").start(); }}@Override
    public void run(a) {
        // Write an infinite loop to simulate
        while (true) {// When the stock is zero, the rush is over
            if (inventory <= 0) {break;
            }
            // Simulate delay, otherwise the results are not easy to see
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("Congratulations!!"+Thread.currentThread().getName()+"-- got a Millet 12! Inventory left:"+inventory+"Taiwan");
            // For each purchase, the stock goes down by 1inventory--; }}}Copy the code
  • The execution result is as follows:

  • Conclusion: The problems that arise

    • The same phone was bought by multiple people
    • We sold more phones than we had in stock
  • With the example above, we can get a general idea of concurrency! This is something we need to pay attention to in real development!


I see no ending, but I will search high and low

If you think I blogger writes good! Writing is not easy, please like, follow, comment to encourage the blogger ~hahah