In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the "summary of relevant knowledge points of threads". In daily operation, I believe many people have doubts about the summary of relevant knowledge points of threads. Xiaobian consulted all kinds of materials and sorted out simple and easy operation methods. I hope it will help you answer the doubts of "summary of relevant knowledge points of threads"! Next, please follow the small series to learn together!
Let's start with the blocking queue, the producer-consumer model.
Give me one example.
In multithreading: so-called blocking, in some cases will suspend threads (i.e. blocking), once the condition is met, suspended threads will automatically wake up.
Why BlockingQueue?
The upside is that we don't need to care about when we need to block threads and when we need to wake threads, because BlockingQueue does it all for you. Before concurrent packages were released, in a multithreaded environment, each of us had to control these details ourselves, especially with regard to efficiency and thread safety, which would bring considerable complexity to our programs.
At the bottom of the thread pool is the blocking queue:
ArrayBlockingQueue: A bounded blocking queue consisting of an array structure.
LinkedBlockingQueue: A bounded (default integer.MAX_VALUE) blocking queue consisting of a linked list structure.
PriorityBlockingQueue: An unbounded blocking queue that supports priority sorting.
DelayQueue: Delay unbounded blocking queue implemented using priority queues.
SynchronousQueue: A blocking queue that does not store elements, i.e. a queue of single elements.
LinkedTransferQueue: An unbounded blocking queue consisting of a linked list structure.
LinkedBlockingDeque: A bi-directional blocking queue consisting of a linked list structure
Say SynchronousQueue, unlike other BlockingQueue, SynchronousQueue is a BlockingQueue that stores no elements (no capacity).
Each put operation must wait for a take operation, otherwise it cannot continue adding elements, and vice versa.
Several ways to create threads
1. Inheriting Thread Class
2. Implementing the Runable Interface
3. Implementation of Callable Interface
Callable FutureTask implements the Runable interface, and the constructor method is passed into Callable (adapter pattern). Interface oriented programming.
4. Thread pool...
ThreadPoolExecutor + blocking queue
1. newCachedThreadPool: used to create a thread pool that can be expanded indefinitely, suitable for light-load scenarios, and perform short-term asynchronous tasks. (This allows tasks to be executed quickly, because the task execution time is short, it can be completed quickly, and it will not cause excessive CPU switching)
2. newFixedThreadPool: Create a thread pool of fixed size. Because of the unbounded blocking queue, the actual number of threads will never change. It is suitable for heavy load scenarios and limits the current number of threads. (Ensure that the number of threads is controllable and will not cause too many threads, resulting in more serious system load)
3. newSingleThreadExecutor: Create a single-threaded thread pool, suitable for ensuring the sequential execution of various tasks.
4. newScheduled ThreadPool: suitable for executing delayed or periodic tasks.
core parameters
1. corePoolSize: Number of resident core threads in the thread pool
maximumPooISize: The maximum number of threads a thread pool can hold simultaneously, this value must be greater than or equal to 1.
keepAliveTime: The time to live of redundant idle threads. When the number of threads in the current thread pool exceeds corepooISize, when the idle time reaches the keepAeTime value, the excess idle threads will be destroyed until only corepooISize threads remain.
Unit: The unit of keepAliveTime
5. workQueue: task queue, tasks submitted but not yet executed
6.threadFactory: Represents a thread factory that generates worker threads in the thread pool. It is generally used to create threads.
7. handIer: Deny policy, indicating the maximum number of threads (maximumPooISize) when the queue is full and the worker thread is greater than or equal to the thread pool
underlying principles
1. After creating the thread pool, wait for the task request to be submitted.
2. When the execute() method is called to add a requested task, the thread pool makes the following determination:
2.1 If the number of threads running is less than corePoolSize, create a thread to run the task;
2.2 If the number of threads running is greater than or equal to corePoolSize, queue the task;
2.3 If the queue is full and the number of threads running is less than maximumPoolSze, create a non-core thread to run the task immediately.
2.4 If the queue is full and the number of running threads is greater than or equal to maximumPoolSze, then the thread pool starts saturation rejection to execute.
3. When a thread completes a task, it takes another task from the queue to execute.
4. When a thread has nothing to do for more than a certain amount of time (keepAliveTime), the thread pool determines:|
If the number of threads currently running is greater than corePoolSize, then the thread is stopped. So the thread pool eventually shrinks to the size of corePoolStze after all its tasks are complete.
refusal strategies
AbortPolicy(default): Throw a RejectedExecutionException to prevent the system from functioning properly.
CallerRunsPolicy: "CallerRun" An adjustment mechanism that does not discard tasks or throw exceptions, but instead rolls back certain tasks to the caller to run.
Discard OldestPolicy: Discard the task waiting the longest in the queue, then add the current task to the queue and try to submit it again.
DiscardPolicy: Discards tasks without handling them or throwing exceptions. This is the best option if you allow the mission to be lost.
Scalability: how do you think about configuring threads properly?
1. CPU intensive
CPU intensive means that the task requires a lot of computation, and without blocking, the CPU is running at full speed.
CPU-intensive tasks can only be accelerated (through multithreading) on a true multicore CPU, and on a single-core CPU, no matter how many simulated multithreads you open, the task cannot be accelerated because the total CPU power is that much.
Because CPU-intensive tasks make CPU usage very high, if too many threads are opened, it will cause excessive CPU switching, so CPU-intensive tasks are configured with as few threads as possible:
General formula: CPU cores + thread pool of 1 thread
2. io-intensive
A slightly larger thread pool can be used, typically 2*CPU cores. IO-intensive tasks CPU usage is not high, so you can let the CPU wait for IO when there are other threads to process other tasks, make full use of CPU time.
Therefore, it is necessary to configure the number of threads:
Reference formula: CPU core number/1-blocking coefficient The blocking coefficient is between 0.8 and 0.9.
For example, 8-core CPU: 8/1-0.9=80 threads
Thread pools Why use blocking queues?
1. Threads created without restrictions may cause excessive memory usage resulting in OOM and excessive CPU switching.
2. Block queue can ensure that there are no tasks in the task queue block the thread to get the task, so that the thread into the wait state, the release of cpu resources. When there is a task in the queue, the corresponding thread is awakened and the message is taken out from the queue for execution. so that threads do not occupy cpu resources all the time.
At this point, the study of "summary of thread-related knowledge points" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!
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.