search
HomeJavajavaTutorialSummary and analysis of multi-threading knowledge in java

Summary and analysis of multi-threading knowledge in java

Sep 18, 2018 pm 05:17 PM
javaMultithreading

This article brings you a summary and analysis of multi-threading knowledge in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Process Overview

  1. Process: A running program is an independent unit for resource allocation and calling by the system.

  2. A process is a dynamic execution process of a program on a data set.

  3. The process generally consists of three parts: program, data set, and process control block.

  4. Each process has its own memory space and system resources.

  5. The program we write is used to describe what functions the process wants to complete and how to complete it;

  6. The data set is what the program does during its execution. Resources to be used;

  7. The process control block is used to record the external characteristics of the process and describe the execution change process of the process. The system can use it to control and manage the process. It is a system-aware process. The unique identifier exists.

  8. Example the process:

(1) Imagine a computer scientist with good cooking skills is baking a birthday cake for his daughter ;
(2) He has a recipe for making a birthday cake and has the necessary ingredients in the kitchen: flour, eggs, sugar, etc.
(3) In this metaphor, the recipe for making a cake is the program;
(4) The computer scientist is the processor cpu;
(5) The various raw materials for making the cake are the input data.
(6) The process is the sum of a series of actions such as the chef reading the recipe, getting various ingredients, and baking the cake.
(7) Now suppose that the computer scientist’s son comes out crying and says that his head was stung by a bee;
(8) The computer scientist records what he did according to the recipe, and It is to save the current state of the process;
(9) Then take out a first aid manual and follow the instructions to deal with the sting;
(10) At this time we will see the processor switching from one process to another High-priority processes;
(11) Each process has its own program (recipes and first aid manuals);
(12) After the bee sting is treated, the computer scientist comes back to make cakes;
(13) Continue from where he left off.

Thread Overview

The emergence of threads is to reduce the consumption of context switching and improve the concurrency of the system.

Threads break through the defect that a process can only do one thing, making intra-process concurrency possible.

Example thread:

(1) Suppose a text program needs to receive keyboard input, display the content on the screen, and save the information to the hard disk.
(2) If there is only one process, it will inevitably cause the embarrassment of being able to do only one thing at the same time, that is, when saving, no keyboard input is possible;
(3) If there are multiple processes, each process is responsible for one Task;
(4) Process A is responsible for keyboard input, process B is responsible for displaying content on the screen, and process C is responsible for saving content to the hard disk;
(5) The collaboration between A, B, and C here involves Process communication issues, and they all have the same content: text content;
(6) Constant switching will cause performance losses.
(7) If there is a mechanism that allows A, B, and C to share resources;
(8) In this way, less content needs to be saved and restored for context switching;
(9) At the same time, It can reduce the performance loss caused by communication.
(10) This mechanism is thread.

Threads are also called lightweight processes.

It is a basic CPU execution unit and the smallest unit in the program execution process.

Composed of thread id, program counter, register set and stack

The introduction of threads reduces the overhead of concurrent execution of programs and improves the concurrency performance of the operating system.

Threads do not have their own system resources.

The relationship between process and thread

  1. A process is a running activity of a program in the computer on a certain data collection.

  2. The process is the basic unit of resource allocation and scheduling in the system and the basis of the operating system structure

  3. The thread is an entity of the process and is The basic unit of CPU scheduling and dispatch

  4. Threads are smaller than processes and can run independently

  5. The relationship between processes and threads:

(1) A thread can only belong to one process, and a process can have multiple threads, but there is at least one thread
(2) Resources are allocated to processes, and the same process All threads share all resources of the process
(3) The cpu is allocated to the thread, that is, the thread is actually running on the cpu

Java program operating principle

  1. ## The #java command will start the java virtual machine, that is, starting the JVM, which is equivalent to starting an application, that is, starting a process;

  2. The process will automatically start a main thread;

  3. Then the main thread calls the main method of a certain class.

  4. So the main method runs in the main thread, and all programs before this are single-threaded

  5. jvm startup is multi-threaded :

(1) Because the garbage collection thread must also be started when the jvm is started, otherwise memory overflow will easily occur;
(2) The current garbage collection thread plus the previous main thread , at least two threads are started, so the startup of jvm is multi-threaded.

The content involving multi-threading is divided into several parts:

  1. Have a good start: the status of the thread

  2. Inner Strength Method: Methods (mechanisms) that each object has

  3. Taizu Changquan: Basic thread class

  4. Nine Yin Manual: Advanced Multi-thread control class

Zhahaomabu: Thread status (five types)

  1. New: New state, when the thread object is created , that is, entering the new state, such as: Thread t = new MyThread()

  2. Runnable: ready state, when the start() method (t.start()) of the thread object is called, The thread enters the ready state. The thread in the ready state only means that the thread is ready and waiting for CPU scheduling execution at any time. It does not mean that the thread will execute immediately after executing t.start()

  3. Running: Running state. When the CPU starts scheduling threads in the ready state, the thread can actually be executed at this time, that is, it enters the running state.

  4. Blocked: Blocked state. The thread in the running state temporarily gives up the right to use the CPU for some reason, stops execution, and enters the blocked state until it enters the ready state. state, there is a chance to be called by the CPU again to enter the running state

  5. Dead: Death state, the thread has finished executing or exited the run() method due to an exception, and the thread ends its life cycle

  6. Note:

    (1) The ready state is the only entrance to the running state
    (2) If a thread wants to enter the running state for execution, it must first be in In the ready state
    (3) According to the cause of the blocking, the blocking state can be divided into three types:
    [1] Waiting for blocking: The thread in the running state executes the wait() method, so that the thread enters the waiting state. Blocking state
    [2] Synchronous blocking: When the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by other threads), it will enter the synchronized blocking state
    [3] Other blocking: By calling the thread's sleep() or When join() or an I/O request is issued, the thread will enter the blocking state. When the sleep() state times out, join() waits for the thread to terminate or times out, or the I/O processing is completed, the thread re-enters the ready state. Method: Each object has methods

    synchronized, wait, and notify are synchronization tools that any object has

  7. monitor:

(1) is applied to synchronization issues Artificial thread scheduling tool

(2) Each Java object has a monitor to monitor the reentrancy of concurrent code.

(3) The monitor does not play a role during non-multithreaded coding. On the contrary, if it is within the synchronized range, the monitor plays a role.

wait/notify: Both must exist in the synchronized block

And these three keywords target the same monitor, which means that after wait, other threads can enter the synchronized block for execution

Taizu Changquan: Basic Thread Class

Thread class

    Runnable class
  1. ##Callable class
  2. Jiuyin Zhenjing: Advanced multi-thread control class
  3. ThreadLocal class:

    (1) Opposite variables used to save threads
  4. (2) When ThreadLocal is used to maintain variables, ThreadLocal is Each thread using the variable provides an independent copy of the variable, so each thread can independently change its own copy without affecting the corresponding copies of other threads.
(3) Commonly used for user login control, such as recording session information.

Atomic class (AtomicInteger/AtomicBoolean)

Lock class: ReentrantLock/ReentrantReadWriteLock.ReadLock/ReentrantReadWriteLock.WriteLock



The above is the detailed content of Summary and analysis of multi-threading knowledge in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor