Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand thread pool in common knowledge points of Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you about how to understand the thread pool in the common knowledge points of Java. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

The basic idea of thread pool is a kind of object pool, which opens up a memory space when the program starts, in which many (undead) threads are stored, and the thread execution scheduling in the pool is handled by the pool manager. When there is a thread task, take one from the pool and return the thread object to the pool after execution, which can avoid the performance overhead caused by repeatedly creating thread objects and save the resources of the system.

one。 Benefits of using thread pools

Reduce resource consumption: reduce the cost of thread creation and destruction by reusing created threads (each thread needs about 1MB memory, and the more threads open, the more memory will be consumed, resulting in a panic).

Improve response time: when a task arrives, it can be executed immediately without waiting for thread creation

Improve the manageability of threads: threads are scarce resources. If created without restriction, it will not only consume system resources, but also reduce the stability of the system. Thread pools can be used for unified allocation, tuning and monitoring.

Some simple management of threads, such as deferred execution, timing cycle execution strategy, etc., can be well implemented by using thread pool.

A thread pool consists of four basic components:

Thread pool manager (ThreadPool): used to create and manage thread pools, including creating thread pools, destroying thread pools, and adding new tasks

Worker thread (WorkThread): a thread in a thread pool that waits when there is no task and can execute the task in a loop.

Task interface (Task): the interface that each task must implement for the worker thread to schedule the execution of the task. It mainly defines the entry of the task, the closing work after the task execution, the execution status of the task, etc.

Task queue (taskQueue): used to store unprocessed tasks. Provides a buffering mechanism.

two。 ThreadPoolExecutor class

When it comes to thread pools, focus on the java.uitl.concurrent.ThreadPoolExecutor class. ThreadPoolExecutor is the core class in the thread pool.

We can create a thread pool through ThreadPoolExecutor

New ThreadPoolExecutor (corePoolSize, maximumPoolSize,keepAliveTime, milliseconds,runnableTaskQueue, threadFactory,handler)

CorePoolSize (basic size of the thread pool): when a task is submitted to the thread pool, the thread pool creates a thread to execute the task, even if other idle basic threads are able to execute the new task, until the number of tasks that need to be executed is greater than the basic size of the thread pool. If the prestartAllCoreThreads method of the thread pool is called, the thread pool creates and starts all basic threads in advance.

MaximumPoolSize (maximum thread pool size): the maximum number of threads allowed to be created by the thread pool. If the queue is full and the number of threads created is less than the maximum number of threads, the thread pool creates new threads to execute the task. It is worth noting that this parameter has no effect if you use an unbounded task queue.

RunnableTaskQueue (task queue): a blocking queue used to hold tasks waiting to be executed.

ThreadFactory: used to set up the factory to create threads, you can use the thread factory to set a more meaningful name for each created thread, Debug and locate problems are very helpful.

RejectedExecutionHandler (deny Policy): when the queue and thread pool are full, indicating that the thread pool is saturated, a strategy must be adopted to deal with new tasks submitted. This policy defaults to AbortPolicy, which means that an exception is thrown when a new task cannot be processed. Here are four strategies provided by JDK1.5. N AbortPolicy: throw an exception directly.

KeepAliveTime (thread activity hold time): the amount of time that the worker thread of the thread pool remains alive after it is idle. So if there are many tasks, and the execution time of each task is relatively short, you can increase this time to improve thread utilization.

TimeUnit (unit of thread activity hold time): optional units are day (DAYS), hour (HOURS), minute (MINUTES), millisecond (MILLISECONDS), microsecond (MICROSECONDS, 1/1000 millisecond) and nanosecond (NANOSECONDS, 1/1000 picosecond).

Submit tasks to the thread pool

We can submit tasks to the thread pool through execute () or submit (), but they are different

The execute () method does not return a value, so it is impossible to determine whether the task was successfully executed by the thread pool

ThreadsPool.execute (new Runnable () {@ Override public void run () {/ / TODO Auto-generated method stub}})

The submit () method returns a future, so we can use this future to determine whether the task is successful or not, and get the return value through the get method of future

Try {Object s = future.get ();} catch (InterruptedException e) {/ / handle interrupt exception} catch (ExecutionException e) {/ / handle task exception} finally {/ / close thread pool executor.shutdown ();}

Closure of thread pool

We can close the thread pool through the shutdown () or shutdownNow () methods, but they are also different

The principle of shutdown is to simply set the state of the thread pool to the state of SHUTDOWN, and then interrupt all threads that are not performing tasks.

The principle of shutdownNow is to traverse the worker threads in the thread pool and then call the thread's interrupt method one by one to interrupt the thread, so a task that cannot respond to the interrupt may never be terminated. ShutdownNow first sets the state of the thread pool to STOP, then attempts to stop all threads that are executing or pausing the task, and returns the list of waiting tasks.

Policies enforced by ThreadPoolExecutor

If the number of threads does not reach corePoolSize, create a new thread (core thread) to execute the task

When the number of threads reaches corePools, the task is moved to the queue to wait

The queue is full, the new thread (non-core thread) executes the task

When the queue is full and the total number of threads reaches maximumPoolSize, an exception will be thrown by (RejectedExecutionHandler)

Four refusal strategies

ThreadPoolExecutor.AbortPolicy () throws a java.util.concurrent.RejectedExecutionException exception

ThreadPoolExecutor.DiscardPolicy () abandons the current task

ThreadPoolExecutor.DiscardOldestPolicy () discards the old task (the first task in the queue is replaced with the current new task execution)

ThreadPoolExecutor.CallerRunsPolicy () retries to add the current task, and he automatically calls the execute () method repeatedly.

three。 Java provides four thread pools through Executors

1. CachedThreadPool (): thread pool can be cached.

Unlimited number of threads

If there are idle threads, the idle threads are reused. If there are no idle threads, the new thread must be created by a certain program to reduce the frequent creation / destruction of threads and reduce system overhead.

CachedThreadPool creates a cacheable thread pool. If the thread pool is longer than the processing needs, it can flexibly recycle idle threads. If there is no reclaim, create a new thread.

2. FixedThreadPool (): fixed-length thread pool.

The maximum number of concurrent threads can be controlled (the number of threads executing at the same time)

Excess threads will wait in the queue

If a thread ends with an execution exception, the thread pool adds a new thread.

3. ScheduledThreadPool ():

Timing thread pool.

Support for scheduled and periodic task execution.

NewscheduledThreadPool creates a fixed-length thread pool that supports scheduled and periodic task execution. The sample code for deferred execution is as follows. Indicates that it is executed every 3 seconds after a delay of 1 second.

Public class ThreadPoolExecutorTest3 {public static void main (String [] args) {ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool (5); scheduledThreadPool.scheduleAtFixedRate (new Runnable () {public void run () {System.out.println (Thread.currentThread (). GetName () + ": delay 1 seconds, and excute every 3 seconds");}, 1,3, TimeUnit.SECONDS) / / indicates that it will be executed every 3 seconds after a delay of 1 second}}

4. SingleThreadExecutor (): a single-threaded thread pool.

One and only one worker thread executes the task

All tasks are performed in the specified order, that is, follow the queuing rules

NewSingleThreadExecutor creates a single-threaded thread pool that only uses a single worker thread to execute tasks, ensuring that all tasks are executed in a specified order (FIFO, LIFO, priority). If the unique thread ends because of an exception, there will be a new thread to replace it. This thread pool ensures that all tasks are executed in the order in which they are submitted.

four。 Monitoring of thread pool

By inheriting the thread pool and overriding the thread pool's beforeExecute,afterExecute and terminated methods, we can do something before the task is executed, after execution, and before the thread pool is closed. Such as the average execution time, the maximum execution time and the minimum execution time of monitoring tasks. These methods are empty in the online pool.

The above is how to understand the thread pool in the common knowledge points of Java. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report