Java—Multithreading (1)

1. Multithreading

Multithreading is a very important way to improve program performance, and a technology that must be mastered.
Using multithreading allows the program to make full use of CPU resources.

1. Advantages

  • System resources are used more reasonably.
  • The program design is more concise.
  • The program responds faster and runs more efficiently.

2. Disadvantages

  • Need more memory space to support multithreading.
  • The situation of concurrent access by multiple threads may affect the accuracy of the data.
  • Data is shared by multiple threads, and deadlock may occur.

Two, process and thread

1. What is a process: A process is an independent application running on the computer.

Process is a dynamic concept. When we start an application, the process is generated. When we close the application, the process ends. The life cycle of the process is the entire process of using the software.

2. What is a thread?

A thread is the basic unit of a process and can perform specific functions. A process is composed of one or more threads.

Applications are static, processes and threads are dynamic, created and destroyed, and existence is temporary, not permanent.

3. The difference between process and thread

Processes have independent memory space at runtime, that is, the memory space occupied by each process is independent and does not interfere with each other.

Threads share memory space, but the execution of each thread is independent of each other, and a single thread cannot be executed. The process controls the execution of multiple threads.

Third, the concept of multithreading

Multithreading refers to the simultaneous execution of multiple threads in a process. The simultaneous execution mentioned here does not mean simultaneous execution in the true sense.

The system allocates CPU resources for each thread. In a specific time period, the CPU resources will be occupied by one thread. In different time periods, different threads will occupy the CPU resources, so multiple threads are still executing alternately. It's just that because the CPU runs too fast, we feel that it is executing at the same time.

If the entire program is a loop, it means that the program has only one thread.

The program has two loops and executes downwards at the same time. In this case, it is multi-threaded, and two threads are executing at the same time.

Use of threads in Java

There are two ways to use threads in Java:

  • Inherit the Thread class
  • Implement Runnable interface

Guess you like

Origin blog.csdn.net/qq_40220309/article/details/105712072