Multithreading in Java
The concept of multithreading in Java has always been complex, general and abstract. The real world only after the knowledge point abstraction can effectively spread, but in the process of communication, only the abstract knowledge point is figurative, we can acquire. So we will dissect the individual content points in a figurative way. When we are finished, we end up abstracting it into nouns: multithreading, resources, locks, etc.
This article only talks about multithreading in Java from the following scope.
1. What is a thread, the role of the thread
2. Control of resources, introduction of locks
3. The role of the thread pool
4. Common tools and methods for multithreading
1. What is a thread
The official explanation: the thread is a single sequential control process.
Threads are divided into the main thread, child threads. Threads are created by the main thread to perform various tasks.
Example: In the anime "Naruto" example, the main thread is like every ninja, they constitute the most basic ninja world, a ninja can follow the task's priorities, the degree of difficulty to perform multiple tasks at the same time. At the same time, the Ninja can also be a part (call their own chakra) to share their own tasks, which is like, Ninja world view of the ninja body, basically equivalent to the main thread in the program. The main thread is gone, and the avatar is not controlled subjectively, it disappears.
From the visible, the main thread and the child thread of the relationship between Ninja and Fen is very similar, that is, the main thread can do things, we can let the sub-thread to help us do. The ninja can do things by himself. Next, let's look at two pieces of code.
The final result of code one and code two is to do only one thing, to output "Hello world!" to the console. But code one is done by the main thread, and code two is done by a child thread created by the main thread. As we can see here, the main thread and the child threads are inherently indistinguishable, because they all perform the same logic, which is not differentiated at all.
If the program is based on a single thread, then all tasks are executed sequentially (serial execution).
The role of multithreading is that you can schedule different threads to perform different tasks.
is a theoretical value, we in some task-intensive scenarios, multi-threaded execution efficiency in most cases may be higher than single-threaded execution.
Why is it possible, because the creation of sub-threads here is to consume performance, but also with time consumption, if the settings are unreasonable, the time cost of creating a child thread is much greater than the time cost of executing the task, which is considered with the actual scenario.
Example: The ninja in the fire shadow will not receive a batch of tasks immediately to do, they also have to combine the actual situation of the task to consider the use of fen.
1. Threads can execute the correct logic code
2. Thread creation is also accompanied by performance consumption, not consumption-free
2. Control of resources
Resources in Java can be understood as any operation of a variable of an instance or underlying data type. Instances or variables can not be fully counted as resources here, because according to the encapsulation in object-oriented programming, it is a taboo to expose an instance directly to an instance of non-class in code.
Here we dissect the relationship between the following resources and threads.
1. A single thread can execute multiple resources (serial)
2. Multiple threads can execute multiple resources (parallel)
3. A single resource can be executed by one thread (crossed)
4. A single resource can be executed by multiple threads (parallel)
From here, 1 and 3 are fine. Because of this mechanism we ensure that a resource is executed by a thread (equivalent to a task being performed by a ninja (ontology or clone). However, 2 and 4 have a phenomenon where the same resource is manipulated by multiple threads and, if unchecked, results in an execution other than that specified, or a deadlock is generated directly.
For example: Two ninjas have performed the same task to kill the leader of a neighboring country, we assume that ninja a used to kill the Boss, Ninja B went after, and found the leader dead, then what will he do next? Did the task fail or did it finish?
Of course Ninja B in the end must still go back to outreach, also count his mission success, this is the task itself rules and order of decision, but the program of the world is not order, need programmers through code to build this disorderly world to form order.
The resources themselves must contain constraints and rules to be used correctly.
Java itself provides control over how resources are dispatched by multiple threads.
synchronized Keywords
· Atomic Bag
· Reentrantlock
· Semaphore
· Countdownlatch
· Cyclicbarrier
· Phaser
Let's go through a chart to get an overview.
The way to control resources is nothing more than a " lock" word. The reality is full of such examples, such as the mayor of a city, according to the rules can only have one, who took office, then the mayor of this resource level is "locked". But the "lock" in the program world differs greatly from the "lock" in the real world.
• The real-world lock is visible, and it controls something as visible as a door, a box, and so on, which is then controlled by objects of an isolated nature to control higher levels of resources, such as: Things in the door, money in the box. In other words, the real-world lock is an indirect control resource.
• The lock in the program world is a more advanced abstraction that contains control over the various dimensions of the resource, which we can interpret as "rules," such as: a class of resources can only have one thread at a time (synchronization), a class of resources must be operated concurrently by multiple threads (synchronous collaboration), A class of resources can have up to n threads to operate (resource scheduling licenses). These are the use of "rules".
There are a lot of things about locks in Java, so let's start with a picture and then focus on the relevant features of each lock.
1. Methods provided by any instance (to avoid direct manipulation of variables as far as possible)
2. We need to use "lock" to control the scheduled rules within the method within the method provided externally.
3. Before implementing the second article be sure to determine the current programming environment, single-threaded or multithreaded
3. thread pool
A phrase that describes the relationship between threads and resources. a person (
Thread
) To Do (
Scheduling
) Something has requirements and rules (
Lock Policy
) The Thing (
Resources
According to the matter (
Resources
) Requirements and Rules (
Lock Policy
) to bind the person to do this (
Thread
) approach.
We use a variety of locking strategies to ensure that resources can be used correctly. Here we also lack an angle, that is, from the perspective of the thread to dispatch resources.
We start the conversation with a question.
• Q: Can we create the number of threads based on the number of resources?
• A: No, because the overhead of creating a thread is limited by the configuration of the machine.
• Q: Then you can create a certain number of threads, to recycle the scheduling resources.
A: This is possible, but the number of resources is generally more than the number of threads, we want to control the scheduling order of resources, not yet time to dispatch resources can be stored in accordance with the first served principle to the queue.
• Q: What to do when the number of resources is less than the number of threads.
• A: We can reserve a certain amount of threads to prepare for future resources that may be dispatched.
This is the prototype of a thread pool, which has the following basic features
1. Maximum number of threads limit
2. There are several standing threads (core threads)
3. If the number of resources exceeds the maximum number of threads, the limit is placed in the queue.
Let's unpack the most complete configuration information for the thread pool:
1. Corepoolsize: Number of core threads
2. Maximumpoolsize: Maximum number of threads
3. KeepAliveTime: The time of thread recycling without resource scheduling (default unit: milliseconds)
4. Timeunit: Time Unit
5. Blockingqueuerunnable: The queue where the extra resources are placed
6. Threadfactory: Thread's factory class
7. Rejectedexecutionhandler: Strategies for thread pool scheduling resources
According to our general settings
Blockingqueue maximumpoolsize≥corepoolsize
Corepoolsize will increase with the number of resource schedules to Maximumpoolsize
• The number of threads (maximumpoolsize-corepoolsize) will be collected according to KeepAliveTime when the thread is idle
· Blockingqueue divided into unbounded queue and bounded queue.
• Placed in Blockingqueue when resource scheduling is greater than maximumpoolsize
o when the blockingqueue is bounded queues are deposited
o when the blockingqueue is unbounded, adjust according to the policy
• When the number of resource schedules is greater than the length of blockingqueue, the resource scheduling is adjusted according to the Rejectedexecutionhandler policy.
o AbortPolicy: Default policy, discards the latest resource schedule, and throws an exception
O Discardpolicy: Discard the latest resource scheduling, no exception
O Discardoldestpolicy: Discard resources in Queue Squadron head
O Callerrunspolicy: To be executed by the main thread ( with caution)
O Custom deny policy: Implement the Rejectedexecutionhandler interface and write a denial policy for a special business.
Summary: A thread pool is a multi-dimensional strategy that is optimized when multiple threads dispatch multiple resources, at the core of which is thread reuse and buffer storage of resources.
?
How to get started with Java multithreading