Getting started with multithreading is so easy

foreword

Spent a week reviewing Java collections before:

Before writing the article, I read through the concurrency chapter of "Java Core Technology Volume 1" and the previous part of "Java Concurrent Programming Practice", and reviewed the notes written before. From today, I will enter the knowledge point of multi-threading~

I was very serious about learning the basics of multithreading when I was learning the basics of Java before, but I never reviewed it later, and I almost forgot about it over time.. I have never used multithreading in learning JavaWeb (I Made something too watery...).

Since this part of the interview accounts for a large proportion, and learning multi-threading is also very helpful for my future improvement (I think).

In fact, I am also equivalent to learning multithreading from scratch. If there are mistakes in the article, please include more, and feel free to correct me in the comment area~~

First, the first understanding of multi-threading

1.1 Introducing the process

Speaking of threads, I have to mention the process again~

We probably know the process very well. Open the Task Manager under Windows and you can find that the programs we run on the operating system are all processes:

Definition of process:

A process is an execution of a program. A process is an activity that occurs when a program and its data are sequentially executed on a processor. A process is a process in which a program with independent functions runs on a data set. It is the system that allocates and schedules resources. an independent unit

  • A process is an independent unit of resource allocation and scheduling in the system. Each process has its own memory space and system resources

1.2 Back to the thread

Then the system has the concept of a process. The process can already allocate and schedule resources. Why do you need threads ?

In order for the program to execute concurrently, the system must perform the following series of operations:

  • (1) Create a process . When the system creates a process, it must allocate all the necessary resources except the processor for it, such as memory space, I/O devices, and establish the corresponding PCB;
  • (2) Cancel the process . When the system cancels the process, it must first perform the recycling operation on the resources occupied by it, and then cancel the PCB;
  • (3) Process switching . When performing context switching on a process, it is necessary to retain the CPU environment of the current process and set the CPU environment of the newly selected process, so it takes a lot of processor time.

It can be seen that when a process implements process scheduling, dispatching, and switching in a multiprocessor environment, it takes a lot of time and space.

The introduction of threads is mainly to improve the execution efficiency of the system, reduce the idle time of the processor and the time of scheduling switching, and facilitate system management. Make the OS have better concurrency

  • To put it simply: the realization of multiprocessing by a process consumes a lot of CPU resources, and we introduce threads as the basic unit of scheduling and dispatching (replacing some of the basic functions of the process [scheduling] ).

So where are the threads? ? for example:

That is to say: multiple tasks can be executed in the same process, and I can see that each task is a thread .

  • So: a process will have 1 or more threads !

1.3 Processes and threads

So we can conclude:

  • Process as the basic unit of resource allocation
  • As the basic unit of resource scheduling , a thread is the execution unit and execution path of a program (single thread: one execution path, multithreading: multiple execution paths). It is the most basic unit of the program using the CPU.

A thread has 3 basic states :

  • execute, ready, blocking

Threads have 5 basic operations :

  • Fork, Block, Activate, Dispatch, End

Thread properties:

  • 1) Lightweight entities;
  • 2) The basic unit of independent scheduling and assignment;
  • 3) can be executed concurrently;
  • 4) Shared process resources.

There are two basic types of threads :

  • 1) User-level thread : The management process is all completed by the user program, and the core in the operating system only manages the process.
  • 2) System-level threads (core-level threads): managed by the operating system kernel . The operating system kernel provides corresponding system calls and application program interface APIs to application programs, so that user programs can create, execute and cancel threads.

It is worth noting that the existence of multithreading does not improve the execution speed of the program. In fact, in order to improve the utilization rate of the application, the execution of the program is actually robbing the resources of the CPU and the execution right of the CPU. Multiple processes are robbing this resource, and if one of the processes has more execution paths , it will have a higher chance of grabbing the execution right of the CPU.

1.4 Parallelism and Concurrency

parallel:

  • Parallelism refers to the occurrence of two or more events at the same time .
  • Parallelism is multiple events on different entities

Concurrency:

  • Concurrency is when two or more events occur within the same time interval .
  • Concurrency is multiple events on the same entity

It can be seen that parallelism is for processes, and concurrency is for threads .

1.5 Java implements multithreading

The above said a lot of basics, understand the words. Let's go back to Java and see how Java implements multithreading~

Java uses the Thread class to implement multithreading. Let's take a look at the top annotation of the Thread class :

From the top comment above, we can see that there are two ways to create multithreading :

  • Inherit Thread and override the run method
  • Implement the Runnable interface and override the run method

1.5.1 Inherit Thread and override the run method

Create a class, inherit Thread, and override the run method


public class MyThread extends Thread {

    @Override
    public void run() {
        for (int x = 0; x < 200; x++) {
            System.out.println(x);
        }
    }

}

Let's call the test to see:


public class MyThreadDemo {
    public static void main(String[] args) {
        // 创建两个线程对象
        MyThread my1 = new MyThread();
        MyThread my2 = new MyThread();

        my1.start();
        my2.start();
    }
}

1.5.2 Implement the Runnable interface and rewrite the run method

Implement the Runnable interface and override the run method


public class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int x = 0; x < 100; x++) {
            System.out.println(x);
        }
    }

}

Let's call the test to see:


public class MyRunnableDemo {
    public static void main(String[] args) {
        // 创建MyRunnable类的对象
        MyRunnable my = new MyRunnable();

        Thread t1 = new Thread(my);
        Thread t2 = new Thread(my);

        t1.start();
        t2.start();
    }
}

The result is still the same as above , so I won't post the picture here~~~

1.6 Details that need to be paid attention to when implementing multithreading in Java

Don't confuse run()withstart()

The difference between run() and start() methods:

  • run(): Just encapsulate the code executed by the thread , and the direct call is a normal method
  • start(): The thread is started first , and then the run() method of the thread is called by the jvm.

Is the startup of the JVM virtual machine single-threaded or multi-threaded?

  • is multithreaded . Not only will the main thread be started, but at least the garbage collection thread will be started. Otherwise, who will help you reclaim unused memory~

So, since there are two ways to implement multithreading, which one do we use ? ? ?

Generally we use to implement the Runnable interface

  • The limitation of single inheritance in java can be avoided
  • The concurrent running task and the running mechanism should be decoupled , so we choose to implement the Runnable interface this way!

2. Summary

This article mainly explains what threads are, and understanding the basics of threads is helpful for our future learning. Here is mainly a simple entry into the door

When reading the comments at the top, we found that there are words such as "priority" and "background thread". This article does not explain what they are ~ so the next article will mainly explain the API of Thread ~ please look forward to it ~

Using threads will actually cause our data to be unsafe, and even the program cannot run. These problems will be explained later~

When I was learning the operating system before, I also took some notes based on the book "Computer Operating System - Tang Xiaodan", which are relatively simple knowledge points . Maybe it will help you~

References:

  • "Java Core Technology Volume 1"
  • "Java Concurrent Programming Practice"
  • "Computer Operating System - Tang Xiaodan"

If there are any mistakes in the article, please correct me, and we can communicate with each other. Students who are used to reading technical articles on WeChat and want to get more Java resources can follow WeChat public account: Java3y . For everyone's convenience, I just created a new QQ group: 742919422 , you can also go to communicate. Thank you for your support! Hope to introduce more to other friends in need

Table of Contents Navigation for Articles :

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324521028&siteId=291194637