[JavaEE] Detailed explanation of the difference between thread and process


Column introduction: JavaEE from entry to advanced

Topic source: leetcode, Niuke, Jianzhi offer.

Creation goal: record the learning process of learning JavaEE

I hope to help others while improving myself, and make progress together with everyone and grow up with each other.

Academic qualifications represent the past, ability represents the present, and learning ability represents the future! 


Table of contents

Understanding threads (Thread)

1. What is a thread?

2. Why are there threads?

3. What is the difference between thread and process?

4. The relationship between Java threads and operating system threads 

5. Create multiple threads

6. Use JConsole to view thread status


Understanding threads (Thread)

1. What is a thread?

A thread is an execution flow, each thread can execute code in its own order, and multiple threads execute multiple copies of code at the same time .

For example: Zhang San, an accountant of a company, goes to the bank to handle business. The business scope is very wide, including financial transfer, social security payment, and employee benefit distribution. If Zhang San is the only accountant, it will take a long time. In order to save time, the company Zhang San called Li Si and Wang Wu again, and the three queued up to call their numbers. Since then, there have been three execution streams to complete the task together, but in essence they still handle the business of the same company. Called multi-threading, a large task is divided into multiple small tasks, which are queued for execution by different execution flows. Among them, Li Si and Wang Wu are called by Zhang San, so Zhang San is the main thread. (Main Thread).


2. Why are there threads?

First of all, " concurrent programming " has become " just needed ".

  • The development of single-core CPU has encountered a bottleneck. If you want to increase the computing power, you need to use multi-core CPU. And concurrent programming can just make full use of multi-core CPU resources.
  • Some tasks often need to wait for "IO". In order to let the program do some other work while waiting for "IO", concurrent programming is also required.

Second, although multiple processes can achieve concurrent programming, threads are lighter than processes.

  • Creating threads is faster than processes
  • Scheduling threads is faster than processes
  • Destroying threads is faster than processes

 Tips: Although threads are lighter than processes, people are not satisfied with this, so there are "thread pool" (Thread Pool) and coroutine (Coroutine)


3. What is the difference between thread and process?

dimension multi-Progress Multithreading Summarize
data sharing, synchronization

Data is separated and shared complex;

Synchronization is simple.

Multi-thread sharing process data, sharing is simple;

Synchronization complex

Each has its own advantages
memory, cpu

Occupies a lot of memory and low CPU utilization

Occupies less memory, high CPU utilization

thread dominant
create destroy switch Create and destroy, complex switching, slow speed Create and destroy, easy to switch, fast thread dominant
programming debugging Easy programming, easy debugging Programming is complex, debugging is complex process dominant
reliability Processes do not affect each other

A thread hang will result in

The whole process hangs

process dominant
distributed

Suitable for multi-core, multi-machine distribution;

If one machine is not enough, 

Scaling to multiple machines is relatively simple

Suitable for multi-core distribution thread dominant
  • Processes contain threads, and each process has at least one thread, the main thread.
  • The memory space is not shared between processes, and multiple threads of the same process share the same resources of the process. (Memory and file descriptor table)
  • A process is the smallest unit of resource allocation by the system, and a thread is the smallest unit of system scheduling .

Still the previous example, each customer who comes to the bank to handle business is equivalent to a process, and their bills must be different, otherwise the money in the bank card will be taken away by others, and although Zhang, San, Li, Si, Wang and Wu are three different execution flows, But all the businesses are handled by the same company, so the bills are shared, which is the biggest difference between multi-thread and multi-process.


4. The relationship between Java threads and operating system threads 

Thread is a concept in the operating system. The operating system kernel implements such a mechanism as thread, and provides a series of APIs for use by the user layer, such as the pthread library of the Linux system.

The Thread class in the Java standard library can be seen as a further abstraction and encapsulation of the thread API provided by the operating system.


5. Create multiple threads

1) Inherit Thread and rewrite run()

t.start actually creates a thread, which is an independent execution flow. run() just describes what tasks the thread will perform, 

class MyThread extends Thread{
    @Override
    public void run(){
            System.out.println("Hello thread");
    }
}
public static void main(String[] args) {
        Thread t = new MyThread();
        t.start();//start 创建了一个新的线程 , 新的线程负责执行t.run().
        System.out.println("Hello main");
      
    }

2) Implement Runnable()

Separate tasks from threads, and decouple threads from tasks. (Low coupling) The advantage is that if you want to change to multi-process, or thread pool, or coroutine later... at this time, the code changes are relatively small.

 class MyRunnable implements Runnable {
    //Runnable 作用 , 描述一个"要执行的任务" , run 方法就是任务执行的细节.
    @Override
    public void run() {
        System.out.println("Hello Thread");

    }
}
public static void main(String[] args) {
        //描述一个任务
        Runnable runnable = new MyRunnable();
        //把任务交给线程来执行
        Thread t = new Thread(runnable);
        t.start();
    }

3) Use anonymous inner classes

new Thread creates a subclass of the Thread class, since the subclass does not have an inner class named anonymous, and makes the t reference point to that instance.

public static void main(String[] args) {
        Thread t = new Thread(){
            @Override
            public void run(){
                System.out.println("Hello thread");
            }
        };
        t.start();
    }

4) Implement Runnable() using an anonymous inner class

This method is essentially the same as the second method. Only the task of implementing Runnable is handed over to the anonymous inner class. Finally, the instance of the anonymous inner class is handed over to the constructor of the Thread class.

public static void main4(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello thread");
            }
        });
        t.start();
    }

5) Simple way of writing Lambda expression

Pass the lambda directly to the Thread constructor.

 public static void main5(String[] args) {
        Thread t = new Thread(()->{
            System.out.println("Hello world");
        });
        t.start();
    }

6. Use JConsole to view thread status

JConsole is a JMX-based visual monitoring and management tool that comes with jdk. It is mainly used to view the status of threads.

Open jdk, enter the bin directory, and find jconsole.

jconsole can only view the status of the running thread, we first run a multi-threaded Java program in the local ideal. At this time, open jconsole to find the Java program we created, and click Connect.

 Ignore the insecure connection prompt and go to the thread column.

 At this point we can see multiple threads, where main is the main thread, and Thread-0 is another thread we created. The rest of the threads are all built into the JVM.

 After selecting the specified thread, you can view the specific execution details of the thread call stack in the stack trace. This is very useful for the later debugging of multi-threaded programs.

Guess you like

Origin blog.csdn.net/liu_xuixui/article/details/128410584