Multi-threaded and concurrent programming [Multi-threaded and concurrent programming, the difference between processes and threads, and the creation of threads] (1)-Comprehensive and detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

Multithreading and Concurrent Programming

 The difference between process and thread

 Execution Characteristics of Threads and Methods

 What is the main thread and sub-thread

 thread creation

 Multi-threading through the Runnable interface

The execution flow of the thread

 Thread state and life cycle

 use of threads


 

Multithreading and Concurrent Programming

 Introduction to Multithreading

What is a program?

Program (Program) is a static concept, generally corresponding to an executable file in the operating system.

 What is a process?

The program in execution is called a process (Process), which is a dynamic concept. In fact, a process is a program space that runs independently in memory.

 Modern operating systems such as Mac OS X, Linux, Windows, etc., all support "multitasking" operating systems, what is called "multitasking"? Simply put, the operating system can run multiple tasks at the same time. For example, you are browsing Taobao, listening to music, and chatting on WeChat at the same time. This is multitasking, and at least three tasks are running at the same time. There are still many tasks running quietly in the background at the same time, but they are not displayed on the desktop.

 What are threads?

Thread (Thread) is the smallest unit that the operating system can perform operation scheduling. It is included in the process and is the actual operating unit in the process.

Some processes do more than one thing at the same time, such as WeChat, which can perform typing chat, video chat, Moments and other things at the same time. Inside a process, if you want to do multiple things at the same time, you need to run multiple "subtasks" at the same time. We call these "subtasks" in the process threads (Thread).

 The difference between process and thread

A story illustrates the relationship between processes and threads

 Jobs wanted to open a factory to produce mobile phones, and he worked hard to build a production line with many devices and materials. A production line is a process. Only the production line is not enough, so find five workers for production, this worker can use these materials to finally make the mobile phone step by step, these five workers are five threads.

In order to increase productivity, there are two ways:

1. Recruit more workers on a production line to make mobile phones together, so that the efficiency will increase exponentially, that is, the single-process multi-thread method

2 Multiple production lines, multiple workers on each production line, that is, multi-process and multi-thread

 

 1 Thread is the smallest unit of program execution, and process is the smallest unit of resource allocation by the operating system;

 2 A process is composed of one or more threads, and a thread is a different execution route of code in a process;

 3 The processes are independent of each other, but the memory space of the program (including code segments, data sets, heaps, etc.) and some process-level resources (such as open files and signals) are shared between threads under the same process. Threads are not visible to other processes;

 4 Scheduling and switching: Thread context switching is much faster than process context switching.

 what is concurrency

Concurrency means doing multiple things at the same time at the same time. When there are multiple threads running, if there is only one CPU, the computer operating system will use concurrency technology to achieve concurrent operation in this case. The specific method is to use the "time slice polling algorithm". , other threads are in a ready state. This way we call it concurrency. (Concurrent).

 

 1 Serial (serial): On one CPU, multiple tasks are completed in sequence

 2 Parallelism (parallelism): refers to the number of tasks is less than or equal to the number of cpu cores, that is, the tasks are really executed together

 3 Concurrency: A CPU uses time slice management to process multiple tasks alternately. Generally, the number of tasks exceeds the number of CPU cores. Through various task scheduling algorithms of the operating system, multiple tasks can be executed "together" (in fact, there are always some tasks that are not being executed, because the switching speed of tasks is quite fast, and they seem to be executed together. execution only)

 Execution Characteristics of Threads and Methods

Method Execution Characteristics

 Execution characteristics of threads

 What is the main thread and sub-thread

 main thread

When a Java program starts, a thread will run immediately. This thread is usually called the main thread of the program (main thread), that is, the thread corresponding to the main method, which is executed when the program starts. A Java application will have a main method, which appears as a method of a certain class. When the program starts, this method will be the first to be automatically executed and become the main thread of the program. In other words, the main method is the entry point of an application and also represents the main thread of the application. When the JVM executes the main method, the main method will enter the stack memory, and the JVM will open up an execution path from the main method to the cpu through the operating system, and the cpu can execute the main method through this path, and this path has a name called main (main) thread

 Features of the main thread

It is the thread that spawns other child threads. It is not necessarily the last thread to finish executing, and child threads may still be running after it finishes.

 child thread

Threads created and started in the main thread are generally called sub-threads.

 thread creation

Realize multi-threading by inheriting the Thread class

 Steps to inherit the Thread class to implement multi-threading:

1 The class responsible for implementing the thread function in Java is the java.lang.Thread class.

Disadvantage of this method: If our class has already inherited a class (for example, the applet must inherit from the Applet class), it cannot inherit the Thread class.

2 You can create a new thread by creating an instance of Thread.

3 Each thread completes its operation through the method run( ) corresponding to a specific Thread object, and the method run( ) is called the thread body.

4 Start a thread by calling the start() method of the Thread class.

 Realize multi-threading by inheriting the Thread class

public class TestThread extends Thread {
//自定义类继承Thread类
 //run()方法里是线程体
 public void run() {
   for (int i = 0; i < 10; i++) {
       System.out.println(this.getName() + ":" + i);//getName()方法是返回线程名称
    }
 }
 public static void main(String[] args) {
      TestThread thread1 = new TestThread();//创建线程对象
      thread1.start();//启动线程
      TestThread thread2 = new TestThread();
      thread2.start();
   }
}

 Multi-threading through the Runnable interface

 In development, we use more multi-threading through the Runnable interface. This method overcomes the disadvantage of inheriting the Thread class, that is, it can also inherit a certain class while implementing the Runnable interface. From the perspective of source code, the Thread class also implements the Runnable interface. The source code of the Runnable interface is as follows:

public interface Runnable {
     void run();
}

Comparing the two methods, the way to implement the Runnable interface is more general.

 Multi-threading through the Runnable interface

public class TestThread2 implements Runnable
{
    //自定义类实现Runnable接口;
    //run()方法里是线程体;
 public void run() {
      for (int i = 0; i < 10; i++) {
 
      System.out.println(Thread.currentThread().getName() + ":" + i);
    }
 }
 public static void main(String[] args) {
        //创建线程对象,把实现了Runnable接口的对象作为参数传入;
     Thread thread1 = new Thread(new TestThread2());
     thread1.start();//启动线程;
     Thread thread2 = new Thread(new TestThread2());
     thread2.start();
 }
}

The execution flow of the thread

 Thread state and life cycle

 A thread object needs to go through 5 states during its life cycle.

  1 Freshman status (New)

         After using the new keyword to create a thread object, the thread object is in a new state. The thread in the new state has its own memory space, and enters the ready state by calling the start method.

 2 Ready state (Runnable)

        The thread in the ready state already has the running conditions, but has not been allocated to the CPU, and is in the "thread ready queue", waiting for the system to allocate a CPU to it. The ready state is not the execution state. When the system selects a Thread object waiting to be executed, it will enter the execution state. Once the CPU is obtained, the thread enters the running state and automatically calls its own run method. There are 4 reasons why a thread enters the ready state:

     2.1 Create a new thread: call the start() method to enter the ready state;

     2.2 Blocked thread: Unblock and enter the ready state;

     2.3 Running thread: Call the yield() method to directly enter the ready state;

     2.4 Running thread: JVM switches CPU resources from this thread to other threads.

3 Running status (Running)

  A thread in the running state executes the code in its own run method until it terminates by calling other methods or waits for a resource to block or completes the task and dies. If the execution does not end within a given time slice, it will be replaced by the system and return to the ready state. It is also possible to enter a blocked state due to some "blocking-causing event".

4 Blocked state (Blocked)

  Blocking refers to suspending the execution of a thread to wait for a certain condition to occur (such as a resource is ready).

  There are 4 reasons for blocking:

  4.1 Execute the sleep(int millsecond) method to make the current thread sleep and enter the blocking state. When the specified time is up, the thread enters the ready state.

 4.2 Execute the wait() method to make the current thread enter the blocking state. When the thread is woken up using the notify() method, it enters the ready state.

 4.3 When the thread is running, an operation enters the blocking state, such as performing an IO stream operation (the read()/write() method itself is a blocking method). The thread enters the ready state only when the reason that caused the operation to block has disappeared.

 4.4 join() thread union: When a thread waits for another thread to finish executing before continuing to execute, use the join() method.

5 Death state (Terminated)

The dead state is the last stage in the thread life cycle. Threads die for two reasons. One is that the normal running thread has completed all the work in its run() method; the other is that the thread is forcibly terminated, such as terminating a thread by executing the stop() or destroy() method (Note: stop()/destroy( ) method has been deprecated by JDK and is not recommended). When a thread enters the dead state, it cannot return to other states.

 use of threads

Typical way to terminate a thread

 To terminate threads, we generally do not use the stop()/destroy() methods provided by JDK (they themselves are also abandoned by JDK). The usual way is to provide a boolean termination variable, and when this variable is set to false, the running of the thread will be terminated.

 Typical way to terminate a thread

public class StopThread implements Runnable
{
    private boolean flag = true;
    
   @Override
    public void run() {
       System.out.println(Thread.currentThread().getName()+" 线程开始");
            int i= 0;
            while(flag){              
       System.out.println(Thread.currentThread().getName()+" "+i++);
                try {
                    Thread.sleep(1000);
               } catch(InterruptedException e) {
                    e.printStackTrace();
               }
           }
      
       System.out.println(Thread.currentThread().getName()+" 线程结束");
   }
    public void stop(){
        this.flag = false;
   }
    public static void main(String[]args)throws Exception {
        System.out.println("主线程开始");
        StopThread st = new StopThread();
        Thread t1 = new Thread(st);
        t1.start();
        System.in.read();
        st.stop();
        System.out.println("主线程结束");
   }
}

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131648074