In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to implement multithreading in java? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
I. Overview
To understand multithreading, you have to understand threads, and to understand threads, you have to understand processes.
1. Process
A program that is being executed.
The execution of each process has an execution order, which is an execution path, also called a control unit.
two。 Thread
The independent control unit in a process is called a thread.
Threads control the execution of the process.
As long as there is a thread executing in the process, the process does not end.
There is at least one thread in a process.
3. Multithreading
When the Java virtual machine starts, there is a java.exe executor, that is, a process.
There is at least one thread in this process responsible for the execution of the java program, and the running code of this thread is stored in the main method, which is called the main thread.
When JVM starts, in addition to executing a main thread, it also starts the thread responsible for the garbage collection mechanism.
The way in which multiple threads execute in a process is called multithreading.
4. The significance of multithreading
Multithreading can make the program run at the same time, and can improve the efficiency of program execution.
When the java.exe process executes the main program, if there is a lot of code in the program, many objects will be generated in the heap memory, and the objects will become garbage after the call. If there is too much garbage, it may lead to insufficient heap memory and affect the running of the program. In this case, if there is only one thread running processing, the efficiency of program execution is very low; if there are multiple threads helping with processing, the efficiency of program execution will be greatly improved.
For example, if the thread of the garbage collection mechanism is helping with garbage collection, the release of memory space in that pile will be much faster.
For example:
5. The principle of CPU operation
There are many programs on PC "at the same time". It looks as if CPU is dealing with all programs "at the same time". In fact, a single-core CPU can only run one program at the same time. It seems that the effect of running at the same time is just CPU switching quickly between multiple threads.
The program that CPU executes, or which program grabs the execution power of CPU, will be executed. CPU will not only execute one thread, but will execute another, or another thread will take away the execution power of CPU. It is up to CPU to decide how to execute it.
There is no rule about which program CPU executes, which is a multithreaded feature: randomness.
Second, the mode of creation
How to create threads: inheritance and implementation.
1. Inherit
A class for thread description, Thread, is already available in Java. Inherit the Thread class, override (override) the run method, and create threads.
Steps:
Start the thread and call the run method.
Note: if the object calls the run method directly, only one thread is executing, and the custom thread is not started.
It is equivalent to creating a thread.
The custom code is stored in the run method and let the thread execute.
Define class inheritance Thread
Override (override) the run method in Thread
Create an instance object of a custom class
The instance object calls the thread's start method.
The reason for overriding (overriding) the run method: the Thread class is used to describe a thread, and a function is defined in the class to store the code that the thread is going to execute. The run method stores this function. In summary, the run method in Thread is used to store the code that the thread is going to execute.
For example:
The results are as follows
Note: threads are executed randomly and alternately, and the results of each run are different.
two。 Realize
The drawback of using inheritance Thread to create a thread is that if the class inherits another parent class, you cannot use Thread to create a thread, so you create a thread by implementing the Runnable interface. Implement the Runnable interface, override (override) the run method, and create threads.
Steps:
The start method automatically calls the run method of the Runnable subclass.
The reason for passing a subclass object of Runnable to the constructor of Thread:
The object to which the custom run method belongs is a subclass object of Runnable. In order for the thread to specify the run method of the object, you must know the object to which the run method belongs.
The custom code is stored in the run method and let the thread execute.
Define a class to implement Runnable
Override (override) the run method in Runnable
Create a thread object through the Thread class.
Pass a subclass object of Runnable as an actual parameter to the constructor of Thread
Call the start method in Thread to start the thread.
Benefit: avoids the limitations of single inheritance. (when defining threads, it is recommended to give priority to)
For example:
The results are as follows:
Note: threads are executed randomly and alternately, and the results of each run are different.
Third, the difference and status 1. The difference in the way it is created
Inheritance: thread code is stored in the run method of the Thread subclass.
Implementation: the thread code is stored in the run method of the Runnable subclass.
two。 Status
Created: wait for startup, call start to start.
Running status: it has the qualification and power of execution.
Temporary status (blocking): has the qualification to execute, but does not have the right to execute.
Frozen state: when the sleep (time) method and the wait () method are encountered, the execution qualification and power are lost; when the time of the sleep method ends or when the notify () method is called, the execution qualification is obtained and becomes a temporary state (blocking).
Extinct state: call the stop () method or the run method to end.
Note: after the thread has gone from the created state to the running state, it doesn't make any sense when the start () method is called again, and the Java runtime will prompt the thread that the state is abnormal.
Fourth, security issues 1. Reason
When multiple statements operate the shared data of the same thread, one thread only executes part of the multiple statements, and when the execution is not completed, other threads participate in the execution, which will lead to the error exception of the shared data, that is, the safety problem of the thread.
All in all:
The randomness of threads.
There is a delay in multiple thread access.
Note: thread safety problems are generally not easy to occur in an ideal state, but once thread safety problems occur, it will have a great impact on the program software.
two。 Synchronization
For thread safety, only one thread is allowed to execute statements that share data for multiple operations, and then the next thread is allowed to execute. No other thread can participate in the execution of each thread in the process of execution.
Java provides a professional solution-synchronized (synchronization).
Solution: synchronize code blocks and synchronization functions. (all are implemented using the keyword synchronized)
Format:
Synchronized {code that needs to be synchronized;}
The fundamental reason why synchronization can solve the problem of thread safety is that on the object, if a synchronization lock is added to the object, the thread that holds the lock can execute in synchronization, and the thread that does not hold the lock cannot enter and execute even if it acquires the right to execute CPU, because it does not acquire the synchronization lock.
For example:
Synchronization code block
Premise:
There must be two or more threads
Multiple threads must use the same lock.
Pros and cons:
Benefit: the safety problem of multithreading is solved.
Disadvantages: multiple threads need to judge locks, consume resources, and affect efficiency.
How to find the security problem of multithreading?
Explicitly share data
Make it clear which code is multithreaded
Identify which statements in multithreaded code operate on shared data.
3. Synchronization of static functions
After the synchronization function is modified by statics, the synchronization lock used is no longer this, because this cannot be defined in the static function. When statically entering memory, there is no such object in memory, but there must be a bytecode file object corresponding to the class.
For example: class name .class (object type is Class)
The synchronization lock used by the static function is the bytecode file object of the class.
Class name .class
For example:
4. Deadlock
When synchronization is nested in synchronization, deadlocks may occur.
For example:
Description: the program is stuck and cannot continue execution.
V. Communications
Multiple threads operate on the same resource, but the action of the operation is different, that is, communication between threads.
Operate the same resource synchronously
For example:
Problem points:
When you need to wake up other threads, if you only use notify (), it is easy to wake up only the local thread, which will cause all threads in the program to be in a waiting state.
Wait (): release the execution power of CPU and release the synchronization lock.
Sleep (): releases the execution power of the CPU without releasing the synchronization lock.
For example, a thread with the same lock wait can only be awakened by the notify on the same lock.
These methods exist in synchronization.
The synchronization lock to which you belong must be identified when using these methods
The lock can be any object, and the method called by any object must be defined in the Object class.
Why are wait (), notify (), and notifyAll () used to manipulate threads defined in the Object class?
What's the difference between wait () and sleep ()?
Why define notifyAll ()?
Upgrade solutions for multithreaded synchronous locks are provided in JDK 5 and above
Replace synchronized (synchronization) with Lock, and replace wait (), notify (), notifyAll () in the Object class with Condition objects.
Condition objects can be obtained through Lock (locks) and support multiple related Condition objects.
For example:
Note: as long as you assign false to the tag flag in the main function or other thread, you can let the run () method end and the thread stop.
Special case: when a thread is frozen and the code in the run () method cannot be read, the thread cannot be stopped.
The frozen state of the thread needs to be cleared to force the thread to resume running. Interrupt () is provided in the Thread class.
For example:
7. What circumstances require multithreading?
When some code needs to be executed at the same time, it can be encapsulated by a separate thread and run with multiple threads.
For example
VIII. Expansion
Join ()
When the A thread executes to the join (); method of the B thread, the A thread waits, and after the B thread finishes execution, the A thread continues to execute (when the B thread executes alternately with other threads).
Temporarily join a thread to execute:
SetPriority ()
MIN_PRIORITY: lowest priority 1
MAX_PRIORITY: highest priority 10
NORM_PRIORITY: default priority
Set the priority:
Yield ()
You can pause the current thread to allow other threads to execute.
This is the answer to the question about how to achieve multithreading in java. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.