Java's multithreading elementary

Table of contents

1. Process and thread

1. What is a process

2. Concurrent, parallel and serial

3. Threads and multithreading

4. The difference between process and thread (emphasis)

5. Advantages of multithreading

6. Disadvantages of multithreading

2. Thread creation

1. Inherit the Thread class

2. Implement the Runnable interface and rewrite the run() method

3. Create Thread and implement Runnable by anonymous inner class

4. Implement a thread through Lambda expression

3. View the status of threads created in Java

1. Go directly to the JDK to find the jconsole.exe file

 2. Search jconsole directly on the command line


1. Process and thread

1. What is a process

In computers, a process is an instance of a program that is running. A process is the basic unit for resource allocation and scheduling by the operating system.

Each process has its own independent memory space and data stack , which makes them isolated from each other and avoids data interference between different processes. The operating system manages the scheduling between processes by allocating resources, so that the processes can run in an orderly and concurrent manner. At the same time, processes can also transmit and share data through various communication mechanisms. These communication mechanisms can enable different processes to work together to complete tasks.

A process can be in different states, such as running, ready, blocked, etc., and changes in process state can be caused by internal and external events. Internal events include program running, application and release of resources, etc., while external events include input/output requests, signals, etc. The operating system will switch the process to different states according to different events in order to manage and schedule the process.

2. Concurrent, parallel and serial

Serial (Serial) means that a task or process is completed one by one in order, and after one task is completed, another task starts to execute. For example, a computer needs to process multiple tasks. At this time, serialization means that the next task can only be processed after one task is executed.

Concurrent refers to the alternate execution of multiple tasks within the same time period . On a uniprocessor system , achieving concurrency requires switching between multiple tasks quickly . For example, a computer needs to run multiple applications at the same time, each application has a separate process, and the operating system needs to switch between these processes quickly.

Parallel (Parallel) refers to the simultaneous execution of multiple tasks , and each task runs independently on a different processor . Parallelism requires multiple processors or multiple computers to perform different tasks simultaneously . For example, a large computing task is divided into multiple subtasks, and each subtask is assigned to a different processor or computer for execution.

In computing, the concepts of parallelism and concurrency are often used to improve system performance and responsiveness . By executing multiple tasks or processes simultaneously, the resources of a computer system are utilized to the maximum. Serial, on the other hand, is simpler and more controllable in some cases , such as in the case of a single-threaded program or a small number of tasks .

Let’s take another example in life, when we are eating (task A), the phone rang at this time.

①Serial: We need to finish the meal before answering the phone (task B).

② Concurrency: We will answer the phone later, eat later, and only perform one task at the same time, but we can quickly switch between these two tasks, one will perform task A, and the other will perform task B.

③Parallel: we are eating while answering the phone, task A and task B are carried out at the same time

3. Threads and multithreading

Multithreading refers to the technology of running multiple threads simultaneously in a process . A thread refers to an execution path inside a program. Each thread has its own stack and registers, and can access variables and objects in shared memory. Compared with processes, threads are lightweight, and a process can have multiple threads at the same time .

Why do threads exist?

According to the above definition, we can know that threads are lightweight. The development of multi-threads can solve the problem of resource consumption better than the development of multi-processes. The following are the operations that need to be performed when the process is opened:

This obviously consumes a lot of memory, so there are threads

Creating a thread only focuses on the tasks to be processed, using all the resources applied for when the process is created

Case: Create a factory

Zhang San needs to create a factory to produce daily necessities. He needs to apply for a piece of land in the factory area to create a factory (the CPU allocates resources to the process ). The factory is equivalent to a thread. There are other factories in this factory area, other people's factories ( other threads ), The things they produced before do not affect each other. Then there are required production lines ( threads ) in Zhang San’s factory, which are responsible for producing different products (maybe different production lines produce the same product), and each production line can affect each other ( Threads can affect each other ). The cost of applying for land to create a factory is very high. It is necessary to build a factory building, purchase infrastructure, etc. (the cost of creating a process is very high ), and a production line can be created relatively easily ( the creation of a thread is easier ). Therefore, Zhang San needs to exaggerate production, and priority can be given to creating production lines ( processes )

4. The difference between process and thread (emphasis)

  1. For a process, there is at least one thread (the main thread).
  2. A process is the smallest unit for applying for system resources.
  3. Thread is the smallest unit of CPU scheduling.
  4. Processes do not affect each other, threads can affect each other.

5. Advantages of multithreading

  1. Make full use of CPU resources
  2. Use the characteristics of lightweight threads to reduce system overhead  

    a. The efficiency of thread creation is higher than that of processes b. The efficiency of thread destruction is higher than that of processes c. The efficiency of thread scheduling is higher than that of processes

6. Disadvantages of multithreading

Multithreading can also have some problems

Here we take Xiaodida eating 100 lollipops as an example

If we use multi-process, we need two tables, put 50 lollipops on each table, and then eat

 

If multi-threaded modeling is adopted, it is only necessary to add a few more small dicks to eat on a table.

 

But there may be such a problem, when we continue to increase the number of small dummy, after the small dummy reaches a certain number, this will not only fail to improve efficiency, but will increase the burden on the CPU. Therefore, in a real program, determine the thread The number needs to be tested repeatedly.

 There may also be the following problems

When there is still a lollipop, but there are two little fools. At this time, two little fools compete for a lollipop, and there will be a problem of thread insecurity.

2. Thread creation

The JDK in Java provides us with an API to create threads (Thread class)

1. Inherit the Thread class

public class Demo2_Thread {
    public static void main(String[] args) {
        MyThread02 thread02 = new MyThread02();
        thread02.start();
        while (true){
            System.out.println("main thread");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
class MyThread02 extends Thread{
    @Override
    public void run() {
        while (true){
            System.out.println("my thread ");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

The run() method represents the tasks that need to be performed in this thread

Note: Our custom inherited Thread class rewrites the run() method, and when we start the thread, we call the start() method. If we call the run() method, it is only in the class A method call, and the start() method is to create a thread. Specifically, we can look at the source code start() method.

 The result of running the code

 From the running results of the code, we can conclude that the two threads (main thread main and my thread) are not executed in an orderly manner, because the CPU scheduling is random. The   thread execution is preemptive execution

2. Implement the Runnable interface and rewrite the run() method

public class Demo3_Runnable {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        //创建线程
        Thread thread = new Thread(myRunnable);
        thread.start();
        while (true) {
            System.out.println("main thread");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

class MyRunnable implements Runnable {
    //需要执行的任务
    @Override
    public void run() {
        while (true) {
            System.out.println("生产皮包,金币+1");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
        }

    }
}

Benefits of using Runnable to define tasks:

1. Decoupling, separate defining threads and defining tasks 

2. Separate the definition thread from the definition task so that the code can be modified uniformly when modifying the code

Decoupling: Separate different functions, how to modify or find the code of the specified function can go to the specified location for operation.

3. Create Thread and implement Runnable by anonymous inner class

public class Demo4_Annoation {
    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("hello Thread");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
        thread.start();
        while (true){
            System.out.println("main thread");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

4. Implement a thread through Lambda expression

If you are not familiar with Lambda expressions, you can read this blog: Lambda expressions and Stream API of Java8 new features

public class Demo5_Lambda {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("hello Thread");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
        while (true){
            System.out.println("main thread");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 In fact, this is similar to implementing Runnable, because the Runnable interface is a functional interface, and the method run() has no parameters, so it can be implemented directly with the above format, and the curly braces are the functions that the thread needs to execute

3. View the status of threads created in Java

1. Go directly to the JDK to find the jconsole.exe file

Double-click to open, find the thread you are running to view

Click on an insecure connection to view

 Click the thread above to view your own thread information, the default thread Thread0 starts, you can also name your own thread in the code

A3MUCFZVIdtQAAAAAElFTkSuQmCCwAAACH5BAEKAAAAAAAAAABAAEAAAICRAEAOw==

 2. Search jconsole directly on the command line

Guess you like

Origin blog.csdn.net/qq_64580912/article/details/130497463
Recommended