search
HomeJavajavaTutorialRegain the basics of Java (17): Summary on multi-threading

Regain the basics of java (seventeen): Summary on multi-threading

1. Process

1 . ctrl+shift+esc Task manager window 2. Programs run in the operating system environment and require CPU and memory resources. From the time the program starts running to the time the program is closed, this process is called process 3. The process is in the operating system Unique concept, process = running program 4. A running program corresponds to at least one process 5. Some programs will adopt a multi-process architecture design 7. Processes are independent of each other and cannot access each other or share resources

2. Thread

1. Program-Process Factory 2. The production line in the factory is called a thread 3. A process contains threads, and a thread is a smaller independent Execution unit 4. A process can contain one thread (single-threaded) or multiple threads (multi-threaded) 5. QQ is a program (process), and each chat window opened is a thread 6. Before we The programs written are all single-threaded, and the JVM will automatically treat the main method as a thread (production line) for execution 7. Threads cannot run independently and cannot be executed apart from the process. Multiple threads can share the resources of the process 8. Between threads It is independent

3. Multi-threaded programming

1. The programs we wrote before were all single-threaded, and the JVM will automatically treat the main method as a thread (production line) to execute 2. There are two functions A/B in a program. If multi-thread programming is used, function A can be executed in one thread (production line), and function B can be executed in one thread (production line) 3 . Upload pictures a. Upload one by one b. Upload multiple pictures at the same time 4. Multi-threading further utilizes the resources of CPU and memory, thereby improving the execution efficiency of the program 5. Factory   Thunder

4. CPU and multi-threading

1. Can a student write and watch movies at the same time? The brain switches between writing and watching movies 2. Film movies are very fast, and the brain will create illusions 3. Real "simultaneity" does not exist, the CPU is extremely fast, taking turns, and randomly between multiple threads Switch

5. Java supports multi-threading

1. There are two types of threads in Java: User Thread (user thread) and Daemon Thread (daemon thread) or background service thread). The role of the daemon thread is to provide services for the running of other threads, such as GC threads. 2. Method 1: Inherit the Thread class Method 2: Implement the Runnable interface

6. Method 1

1. The classes we defined before are all ordinary classes , because the codes in these classes cannot be executed at the same time, these classes are not production line classes 2. Java specifically provides a production line class: java.lang.Thread class, the code in this class can be executed at the same time 3. Steps: Let us The custom class inherits the Thread class, and the class we define becomes the production line class. Rewrite the run method in the custom class, and put the code that needs to be executed at the same time into the run method. In the main method, first create the production line, and then Start the production line start()

7. Thread class

public long getId(), get the number of the thread (thread ID), it creates the thread Thread generated. Thread IDs are unique and remain unchanged for life. public final void setName(String name), name the thread, if not named, there will be a default, the format is: Thread-0, Thread-1... public final String getName(), get the name of the thread public void start() , causing the thread to start execution, and the JVM will automatically call the run() method of the thread. public static void sleep(long millis), let the thread sleep (pause) for how many milliseconds public static Thread currentThread(), get a reference to the currently executing thread object. (Method 2 will be used)

8. Multi-threaded execution process

1. The first thing the JVM finds is the main method, and the The code is executed in a thread, which is called the main thread 2. In addition, the thread created manually can be called the child thread 3. The program must wait until all threads have finished executing before it ends

9. Method 2

1. Disadvantages: Method 1 cannot inherit other classes after inheriting the Thread class. Advantages: Simple and easy to implement. 2. Steps: a. We customize The class implements the java.lang.Runnable interface b. Put the code that needs to be executed simultaneously into the run method c. Create a production line (Thread) in main and start it 3. Method 2 does not have the disadvantages of method 1, but is more complicated than method 1

10. Thread safety issues,

1. Under what circumstances will there be thread safety issues? a. Multiple threads are independent of each other b. Multiple threads are operating or using shared resources 2. Multiple threads operate the same shared resource, but the threads are independent of each other and have no contact with each other, so There will be situations where the data is not updated synchronously, which is a thread safety issue. 3. Train ticket selling case Code to be executed at the same time: Sell 10 train tickets Shared resources: 10 train tickets Generally exist as attributes

11. How to solve the thread safety problem

1. Idea: Enter the toilets on the train one by one... 2. Synchronization lock, the professional term is monitoring Monitor3. Java automatically builds a monitor into every object. Locks are everywhere. 4. There are two ways to implement it: Synchronization code block Synchronization method

12. Synchronization Code block

1. First analyze which code needs to be locked 2. synchronized(lock){ }3. The lock used between multiple threads must be the same lock

13. Synchronization method

1. Put the code that needs to be locked into a method first 2. Turn the method into a synchronization method public synchronized void sell(){ Operation The code that shares data is the code that needs to be synchronized;} 3. The lock of the synchronization method is this by default, which is fixed

14. The pros and cons of synchronization lock

Benefits of synchronization: The emergence of synchronization solves the security problem of multi-threading. Disadvantages of synchronization: When there are quite a few threads, because each thread will judge the lock on synchronization, this is very resource-consuming and will virtually reduce the efficiency of the program. operating efficiency. (Performance and thread safety cannot be achieved at the same time)

15. Detailed issues

1. Can static methods be changed to synchronized methods? Yes, but the lock is not this. The bytecode file of the loaded class is Student.class2. The prerequisite for thread safety issues is that shared resources must exist and multiple threads use shared resources. 3. The lock must be the same lock


#The above is the summary of Regaining the Basics of Java (Seventeen): Multithreading. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!


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 to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?How to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?Apr 19, 2025 pm 07:03 PM

How to correctly configure apple-app-site-association file in Baota nginx? Recently, the company's iOS department sent an apple-app-site-association file and...

What are the differences in the classification and implementation methods of the two consistency consensus algorithms?What are the differences in the classification and implementation methods of the two consistency consensus algorithms?Apr 19, 2025 pm 07:00 PM

How to understand the classification and implementation methods of two consistency consensus algorithms? At the protocol level, there has been no new members in the selection of consistency algorithms for many years. ...

What is the difference between IS TRUE and =True query conditions in MySQL?What is the difference between IS TRUE and =True query conditions in MySQL?Apr 19, 2025 pm 06:54 PM

The difference between ISTRUE and =True query conditions in MySQL In MySQL database, when processing Boolean values ​​(Booleans), ISTRUE and =TRUE...

How to avoid data overwriting and style loss of merged cells when using EasyExcel for template filling?How to avoid data overwriting and style loss of merged cells when using EasyExcel for template filling?Apr 19, 2025 pm 06:51 PM

How to avoid data overwriting and style loss of merged cells when using EasyExcel for template filling? Using EasyExcel for Excel...

As a Java programmer, how do you turn to audio and video development? What basic knowledge and resources do you need to learn?As a Java programmer, how do you turn to audio and video development? What basic knowledge and resources do you need to learn?Apr 19, 2025 pm 06:48 PM

How to switch from Java programmers to audio and video development? Learning Paths and Resources Recommendations If you are a Java programmer and are participating in a video project, �...

How to efficiently count the number of node services in MYSQL tree structure and ensure data consistency in Java?How to efficiently count the number of node services in MYSQL tree structure and ensure data consistency in Java?Apr 19, 2025 pm 06:45 PM

How to efficiently count the number of node services in MYSQL tree structure in Java? When using MYSQL database, how to count the number of nodes in the tree structure...

How do newcomers choose Java project management tools for backends: Maven or IntelliJ? Use the Maven that comes with IDEA or an additional download?How do newcomers choose Java project management tools for backends: Maven or IntelliJ? Use the Maven that comes with IDEA or an additional download?Apr 19, 2025 pm 06:42 PM

How do newcomers choose Java project management tools for backends? Newbie who are just starting to learn back-end development often feel confused about choosing project management tools. Special...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment