What is multithreading?

Table of contents

process

thread

Multithreading

implement

concurrent

parallel


process

Process is a dynamic execution process of a program with certain independent functions on a data set. It is an independent unit of resource allocation and scheduling by the operating system. It is an application The carrier on which the program runs. Process is an abstract concept and there has never been a unified standard definition. A process generally consists of three parts: program, data collection, and process control block.

Program: is used to describe the functions to be completed by the process and is a set of instructions to control the execution of the process.

 

Data collection:The data and work area required when the program is executed.

 

Process control block: contains the description information and control information of the process, and is the only sign of the existence of the process.

thread

Thread is the smallest unit that the operating system can perform operation scheduling. Threads are included in processes and are the actual operating units in processes. A process is the basic execution entity of a program and can be understood as a container for threads.

If you think of the process as a restaurant, then the threads are the employees. For a restaurant to operate, its employees must work. The restaurant only provides resources and places, and it is the employees who really serve the guests.

For example, we run the following code.

Run:The restaurant is built and an employee myThread is recruited. The employee's job is to output and print.

End:The restaurant closed down, freeing up resources.

public class Demo {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.setName("线程员工");
        myThread.start();
    }
}

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println(getName() + "打印了:hello world!");
    }
}

result:

The thread employee printed: hello world! 

Multithreading

Since you want to open a restaurant, how can you do it with only one employee? Employees are divided into front desk, chef, and waiter, which means that employees can do different things at the same time and perform their duties. Of course, multiple employees can do the same thing. For example, the waiters are all here to serve the guests, and all they do is serve the guests. But waiters serve guests, and each waiter is independent of each other. You serve your guests, and I serve my guests. But then again, everyone works in the same restaurant, which means resources are shared.

Multi-threading means that the program contains multiple execution streams, that is, multiple different threads can be run simultaneously in one program to perform different tasks. Each thread has its own private registers (such as stack pointer, program counter), but the code area is shared, that is, different threads can execute the same method. Multi-threading technology allows a single program to create multiple threads of parallel execution to complete their respective tasks, thereby improving overall processing performance.

Multi-threading is a mechanism that allows concurrent execution of multiple instruction streams in a program, Each instruction stream is called a thread and is independent of each other. Threads are similar to processes, but are more lightweight and focused on performing a single task. Multithreading is a special form of multitasking that can improve the efficiency of a system, especially when multiple tasks need to be completed simultaneously.

To put it bluntly, the restaurant staff must cooperate well and perform their duties.

In the following code, the work of thread employee 1 and thread employee 2 is output and printing, and they are performed separately. It may be that thread employee 1 completes the output printing first, or it may be thread employee 2. Because the two threads are relatively independent, the result is that they both complete the work, but the order of completion may be different.

public class Demo {
    public static void main(String[] args) {
        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();
        myThread1.setName("线程员工1");
        myThread2.setName("线程员工2");
        myThread1.start();
        myThread2.start();
    }
}

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println(getName() + "打印了:hello world!");
    }
}

result:

Thread employee 1 printed: hello world!
Thread employee 2 printed: hello world!

or

Thread employee 2 printed: hello world!
Thread employee 1 printed: hello world! 

implement

The result of executing the following code is (using multi-threading):

Time consuming: 1ms
The thread employee printed Time consuming: 503ms

public class Demo {
    public static void main(String[] args) {
        long begin = System.currentTimeMillis();

        MyThread myThread1 = new MyThread();
        myThread1.setName("线程员工");
        myThread1.start();

        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - begin) + "ms");
    }
}

class MyThread extends Thread {

    @Override
    public void run() {
        long begin = System.currentTimeMillis();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println(getName() + "打印了耗时:" + (end - begin) + "ms");
    }
}

The result of executing the following code is (without using multi-threading):

The thread employee printed the time taken: 503ms
The time taken: 507ms

public class Demo {
    public static void main(String[] args) {
        long begin1 = System.currentTimeMillis();

        /*MyThread myThread1 = new MyThread();
        myThread1.setName("线程员工");
        myThread1.start();*/

        long begin = System.currentTimeMillis();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("线程员工" + "打印了耗时:" + (end - begin) + "ms");

        long end1 = System.currentTimeMillis();
        System.out.println("耗时:" + (end1 - begin1) + "ms");
    }
}

class MyThread extends Thread {

    @Override
    public void run() {
        long begin = System.currentTimeMillis();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println(getName() + "打印了耗时:" + (end - begin) + "ms");
    }
}

The difference between the two is huge, using multi-threading does not require waiting for the task to complete, but not using multi-threading does.

If we have multiple tasks, we don't need multi-threading. The tasks are executed one by one, which takes a lot of time. Using multi-threading will increase efficiency.

Multithreading is executed concurrently

concurrent

At its simplest and most basic level, concurrency is two or more activities that are performed simultaneously and independently. And we find phenomena throughout our daily lives. We can talk while walking, make different movements with our left and right hands at the same time, and so on.

parallel

When it comes to multithreaded code, the meanings of concurrency and parallelism largely overlap. The difference between concurrency and parallelism is very small, mainly due to different focus and usage intention. Both terms refer to the use of configurable hardware resources to run multiple tasks simultaneously, but parallelism emphasizes performance. When people talk about parallelism, they are mainly concerned about using configurable hardware resources to improve the performance of large-scale data processing; when they talk about concurrency, they are mainly concerned about separation of concerns or responsiveness.

Separation of concerns:Group related code and isolate irrelevant code, making the program easier to understand and test, and therefore more likely to contain fewer defects.

Concurrency to separate concerns, parallelism to improve performance.​ 

Guess you like

Origin blog.csdn.net/qq_74312711/article/details/134965781