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

What is the thread pool principle of java?

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail what the thread pool principle of java is, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

The thread pool has been used before. In use, basically, after initializing the instance of the thread pool, throw the task in and wait for the scheduling to be executed. It is very simple and convenient to use.

New Thread malpractice

Every time new Thread creates a new object, the performance is poor.

Threads lack of unified management, may be unlimited new threads, compete with each other, and may take up too many system resources to cause panic or OOM

Lack of more features, such as more execution, periodic execution, thread interruptions

Benefits of thread pool

Reuse existing threads, reduce the overhead of object creation and demise, and have good performance.

It can effectively control the maximum number of concurrent threads, improve the utilization of system resources, and avoid excessive resource competition and congestion.

Provide advanced functions such as timing execution, periodic execution, single thread, concurrency control and so on.

ThreadPoolExecutor

Parameters:

CorePoolSize: number of core threads. It is recommended that the number of cores is similar to that of cpu. When a task is submitted and the number of threads in the current thread pool is less than corePoolSize, the new thread executes the task without starting reuse, and it will be created until the corePoolSize is reached. When the number of threads in the thread pool is greater than or equal to corePoolSize, the task is put into workQueue to wait.

MaximumPoolSize: the maximum number of threads allowed in the thread pool. When the queue is full, create a new thread if the number of threads in the thread pool is less than maximumPoolSize, and execute the reject policy if greater than or equal to.

If maximumPoolSize is 30 minutes and corePoolSize is 10, only 20 threads can be opened when the queue is full.

WorkQueue: blocking queues, storing tasks waiting to be executed, which is important and can have a significant impact on the thread pool running process

KeepAliveTime: the maximum time for a thread to stop when there is no task to execute. The thread pool maintains the idle time allowed by the thread. When the number of threads in the thread pool is greater than the CorePoolSize, if no new task is submitted, the thread will wait until the time exceeds the keepAliveTime before destroying.

The time unit of the unit:keepAliveTime

ThreadFactory: thread factory, used to create threads, there will be a default factory to create threads. When you create a thread using the default factory, the thread has the same priority and is a non-daemon thread, and the name of the thread is also set.

RejectHandle: the strategy when refusing to process a task. If the workQueue blocking queue is full and there are no idle threads, and the task continues to be submitted, we need a strategy to handle the task. The thread pool provides a total of four strategies:

Throw an exception directly, the default policy

Execute the task with the caller's thread

Discard the top task in the queue and execute the current task

Just drop the task.

If the number of threads running is less than CorePoolSize, create a new thread creation task directly, even if the other threads in the thread pool are idle.

If the number of threads in the thread pool is greater than or equal to CorePoolSize and less than maximumPoolSize, new threads are created to process the task only when the wokQueue is full.

If we set CorePoolSize to be equal to maximumPoolSize, the size of the created thread pool is fixed. If a new task is submitted and the workQueue is not full, put the request into the workQueue and wait for the idle thread to fetch the task from the workQueue for processing.

If the number of threads running is greater than maximumPoolSize, then if the workQueue is full, the policy processing task is specified through a reject policy parameter.

If we want to reduce the consumption of system resources, including the utilization of CPU and operating system resources, we can set a larger workQueue capacity and a smaller CorePoolSize capacity, which will reduce the throughput of threading. If the tasks we submit are often blocked, we can set the maximumPoolSize to set the thread pool capacity. If our queue capacity is small, we usually need to set the maximumPoolSize larger, so that the CPU utilization will be higher. However, if the thread pool capacity is set too large, in the case of too many submitted characters, the concurrency will increase, then inter-thread resource scheduling is a problem to be considered, which will reduce the processing throughput.

Thread pool status

When we initialize a thread pool, we usually have the above states.

Running: you can accept newly submitted tasks or handle tasks in blocking queues.

Shutdown: closed so that when a thread pool instance is in the shutdown state, it can no longer receive newly submitted tasks, but can continue to work on tasks that have been saved in the blocking queue.

Stop: you can't accept new tasks, nor do you handle tasks in the queue. Interrupts the thread task that is being processed.

Tidying: all tasks have been terminated and there are no active threads. When the thread pool is in this state, the hook method terminated () is executed.

Methods in ThreadPoolExecutor

Execute (): submit the task to the thread pool for execution

Submit (): submit the task and return the execution result equivalent to execute+Future

Shutdown (): close the thread pool and wait for all the tasks to be executed

ShutdownNow (): closes the thread pool without waiting for the task to finish execution

GetTaskCount (): total number of executed and unexecuted tasks in the thread pool

GetCompletedTaskCount (): number of tasks completed

GetPoolSize (): the current number of threads in the thread pool

GetActiveCount (): the number of threads in the current thread pool that are executing tasks

Executors framework interface

Executors.newCachedThreadPool: create a cacheable thread pool. If the length of the thread pool exceeds the needs of the thread, you can flexibly recycle the idle thread. If there is no reclaim, you can create a new thread.

Executors.newFixedThreadPool: create a fixed-length thread pool to control the maximum number of concurrency of threads, and excess threads will wait in the queue

Executors.newScheduledThreadPool: also create a fixed-length thread pool. Support for scheduled and periodic task execution.

Executors.newSingleThreadExecutor: create a single-threaded thread pool that uses a unique worker thread to execute tasks. Ensure that all tasks are performed in the specified order (first-in, first-out, etc.).

Executors.newCachedThreadPool sample code:

@ Slf4jpublic class ThreadPoolExample1 {public static void main (String [] args) {ExecutorService executorService = Executors.newCachedThreadPool (); for (int I = 0; I < 10; iTunes +) {final int index = I; executorService.execute (new Runnable () {@ Override public void run () {log.info ("task: {}", index) }});} / / be sure to close the thread pool, otherwise the program will not end executorService.shutdown ();}}

Executors.newSingleThreadExecutor sample code:

@ Slf4jpublic class ThreadPoolExample3 {public static void main (String [] args) {ExecutorService executorService = Executors.newSingleThreadExecutor (); for (int I = 0; I < 10; iTunes +) {final int index = I; executorService.execute (new Runnable () {@ Override public void run () {log.info ("task: {}", index) }});} / / be sure to close the thread pool, otherwise the program will not end executorService.shutdown ();}}

Output result:

17task:017:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:017:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:117:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:217:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:317:08: 16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:417:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:517:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:617:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:717:08:16.875 [ Pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:817:08:16.875 [pool-1-thread-1] INFO com.vincent.example.threadPool.ThreadPoolExample3-task:9

It is equivalent to a single thread executing sequentially.

Executors.newScheduledThreadPool code example:

@ Slf4jpublic class ThreadPoolExample4 {public static void main (String [] args) {ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool (5); scheduledExecutorService.scheduleAtFixedRate (new Runnable () {@ Override public void run () {log.warn ("schedule run");}, 1,3, TimeUnit.SECONDS) / / there is no need to close the thread pool / / scheduledExecutorService.shutdown ();}}

The purpose above is to execute the task every three seconds after a delay of 1 second. Because this task is executed indefinitely, the thread pool should not be closed here. If you need to close the thread pool, you can set a trigger condition to close it. Similar to the Timer class:

@ Slf4jpublic class ThreadPoolExample4 {public static void main (String [] args) {Timer timer = new Timer (); timer.schedule (new TimerTask () {@ Override public void run () {log.warn ("timer run");}}, new Date (), 5x1000);}} reasonable configuration of thread pool

For CPU-intensive tasks, you need to squeeze CPU as much as possible. The reference value can be set to NCPU+1.

For IO-intensive tasks, the reference value can be set to 2*NCPU

We only use thread pool mainly to reuse existing threads, reduce the demise of object creation, effectively control the maximum number of concurrency of threads, and avoid excessive resource competition and blocking. The performance of regular execution of single thread is better than that of control thread. This does not mean that thread pools should be used anytime and anywhere. Be sure to analyze the configuration of parameters according to your actual scenario.

What is the principle of java thread pool is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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