Home Java javaTutorial Regain the basics of Java (17): Summary on multi-threading

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

Jan 16, 2017 am 10:27 AM

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles