[Java Multithreading Explanation-Part 1] To understand multithreading, this article is enough

Foreword: In today's Internet industry, multi-threading technology has become a very important skill. With the development of computer hardware, more and more programmers are paying attention to multi-threading technology, hoping to improve program performance through multi-threading. As a widely used programming language, Java also provides rich multi-threading support. This article will introduce in detail the basic concepts, principles, implementation methods and applications of Java multi-threading in life to help readers better understand and master Java multi-threading technology.

Insert image description here

Introduction to multithreading

Suppose you are cooking in the kitchen and you need to stir-fry two different dishes at the same time. In this scenario, you can think of yourself as a thread, and these two dishes represent the other two threads.

When you fry the first vegetable, you need to cut the vegetable first, then heat the oil in the pot, then add the vegetable into the pot and stir-fry. This is a typical serial process because each step must be performed in order. However, when you fry the second dish, if you still do it this way, then you need to wait for the first dish to complete all the steps before starting the second dish. This is obviously inefficient.

In this case, using multi-threading can improve efficiency. You can prepare the ingredients for the second dish in advance while frying the first dish. While the first dish is still stir-frying in the pot, you can start processing the second dish, such as chopping vegetables, heating oil, etc. This way, you can save a lot of time.

The same principle applies to programming. In the case of a single thread, if the program contains multiple tasks, you must wait until one task is completed before starting the next task. In the case of multi-threading, we can assign different tasks to different threads so that they can run at the same time. This can significantly increase the efficiency of the program.Insert image description here

Thread creation

1. Inherit the Thread class and override the run() method;

First create a class that inherits the Thread class and overrides the run() method. In the run method, write the code to be executed by this thread.

class thread extends Thread{
    
    
    @Override
   public void run(){
    
    
        //thread.currentThread().getName()得到当前线程的名字
        System.out.println("线程启"+thread.currentThread().getName()+"动了");
    }
}

Then create the object and call the start method to start the thread

  public static void main(String[] args) {
    
    
        thread thread = new thread();
        thread.start();
    }

operation result
Please add image description

Implement the Runnable interface and implement the run() method.

First create a class to implement the Runnable interface, and then implement the run() method.

class thread1 implements Runnable{
    
    
    public void run(){
    
    
        System.out.println("线程启"+thread.currentThread().getName()+"动了");
    }
}

Create another Thread object and pass in the object that has implemented the Runnable interface as a parameter. Also start the thread through the start method

  Thread thread1 = new Thread(new thread1());
        thread1.start();

Note In both methods, do not start the thread directly through the run method, because calling the run method directly will only perform tasks on the same thread - it will not create a new thread; In fact, when the start method is called, a thread will be created first and then the run method will be executed

Compare

I suggest you use the second method, let’s take the example of cooking: Suppose you want to cook two dishes now, one is stir-fry and the other is pizza. If you use the first method, you need to create two classes to inherit Thread.

public class Main {
    
    

    public static void main(String[] args) {
    
    
        CookFriedRice cookFriedRice = new CookFriedRice();
        CookPizza cookPizza = new CookPizza();
        cookFriedRice.start();
        cookPizza.start();


    }

}

class CookFriedRice extends Thread{
    
    
    @Override
   public void run(){
    
    
        System.out.println("开始炒菜了!!!");
    }
}
class CookPizza extends Thread{
    
    
    @Override
    public void run(){
    
    
        System.out.println("开始做披萨了!!!");
    }
}

If we implement the Runnable interface to create a thread, then we only need to define two classes that implement the Runnable interface. Don't we also need to create two classes? ? ? Lambda expressions can be used here (unfamiliar friends can read this articlelambda expression)

public class Main {
    
    

    public static void main(String[] args) {
    
    

        new Thread(()-> System.out.println("开始炒菜了!!!")).start();
        new Thread(()-> System.out.println("开始做披萨了!!!")).start();

    }

}

Is the code much simpler, and different threads can operate the same object to achieve information sharing?

public class Main {
    
    

    public static void main(String[] args) {
    
    
        test test = new test();
        Thread thread1 = new Thread(test);
        Thread thread2 = new Thread(test);
        thread1.start();
        thread2.start();

    }

}

class test implements Runnable {
    
    
    private int count = 0;

    public void run() {
    
    
        count++;
        System.out.println(count);
    }
}

Please add image description

3. Thread status

Thread status and life cycle
Threads in Java have 6 states, namely: New, Runnable, Running, and Blocked ), Waiting and Terminated. The life cycle of a thread includes the following stages: new, ready, running, blocked, waiting and terminated.
Insert image description here
Let’s use the example of cooking to help understand:
In the kitchen, the chefs are preparing a dish, and each chef is like an independent task Processor (aka thread). They all have their own list of tasks and work on them in their own order.
The life status of a chef can be divided into the following stages:

New status (New): Chefs are recruited and assigned to the corresponding kitchen area to work.
Ready state (Runnable): The chef is ready to start working, waiting for the chef to assign tasks.
Blocked: The chef is temporarily blocked by other chefs, such as while waiting for the utensils to be cleared.
Running state (Running): The chef starts to prepare the dishes.
Terminated: The chef has completed his task and left the kitchen.

Details:
In fact, after a thread calls start, the program may or may not be traveling far, depending on the system allocated to this Thread time (in the Java specification, traveling is not considered a separate state, and a running thread may also be in a traveling state). The system will allocate a time slice to each thread. When the time slice is used up, the CPU will The opportunity to run will be given to the next thread. Precisely because this process is very fast, we cannot detect the switching process, so that these threads appear to be running at the same time. You can compare a video to a frame-by-frame photo.
Here are a few methods
1.yield (static method)
When the thread is running, the opportunity to run is given up. Give it to other threads (comity), but the courtesy may not be successful. It just gives the running right to the cpu and lets the cpu reschedule
2. join
This method You can block the thread and wait for the child thread to end
See an example

public class Main {
    
    

   public static void main(String[] args) throws InterruptedException {
    
    


       Thread thread1 = new Thread(()-> {
    
    
           for (int i = 0; i < 100; i++) {
    
    
               System.out.println(i+": 子线程在运行!!!");
           }
       });
       thread1.start();
       for (int i = 0; i <100 ; i++) {
    
    
           System.out.println(i+": 主线程在运行!!!");
       }




   }


Running result
Insert image description here
Sub-thread and main thread run concurrently

public class Main {
    
    

    public static void main(String[] args) throws InterruptedException {
    
    


        Thread thread1 = new Thread(()-> {
    
    
            for (int i = 0; i < 100; i++) {
    
    
                System.out.println(i+": 子线程在运行!!!");
            }
        });
        thread1.start();
        for (int i = 0; i <100 ; i++) {
    
    

            if(i%2==0)
                thread1.join();
            System.out.println(i+": 主线程在运行!!!");
        }
        
    }

}

Insert image description here
After adding join, the main thread waits for the child thread to finish before running.

That’s it for this issue. If you think the writing is good, you can pay attention to the next issue.
Next issue preview:

  • Thread synchronization and mutual exclusion
  • Communication between threads
  • Use of thread pool
  • Application of Java multithreading in life

Please add image description

Guess you like

Origin blog.csdn.net/weixin_55939638/article/details/134574254
Recommended