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 > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to use Spring multithreading", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use Spring multithreading" article.
Why use multithreading?
In the process of developing the system, we often deal with some time-consuming tasks (such as inserting a large amount of data into the database), so we need to use multithreading.
Whether the multithreaded method is encapsulated in Springboot
Yes, multithreaded operations can be directly implemented by @ Async in Spring
How to control the parameters in thread running
By configuring the thread pool.
Thread pool ThreadPoolExecutor execution rules are as follows
Then let's think of constructing a thread pool to try:
@ Configuration@EnableAsyncpublic class ThreadPoolConfig implements AsyncConfigurer {/ * * Core thread pool size * / private static final int CORE_POOL_SIZE = 3; / * maximum number of threads that can be created * / private static final int MAX_POOL_SIZE = 10; / * * maximum queue length * / private static final int QUEUE_CAPACITY = 10 / * Thread pool maintains the idle time allowed for threads * / private static final int KEEP_ALIVE_SECONDS = 300; / * Asynchronous execution method thread pool * * @ return * / @ Override @ Bean public Executor getAsyncExecutor () {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor (); executor.setMaxPoolSize (MAX_POOL_SIZE); executor.setCorePoolSize (CORE_POOL_SIZE); executor.setQueueCapacity (QUEUE_CAPACITY) Executor.setKeepAliveSeconds (KEEP_ALIVE_SECONDS); executor.setThreadNamePrefix ("LiMingTest"); / / Thread pool policy executor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()) for denied tasks (wireless paths available); executor.initialize (); return executor;}}
ThreadPoolExecutor is a thread pool implementation in JDK. This class implements all the methods needed for a thread pool. It provides methods for task submission, thread management, monitoring, and so on.
CorePoolSize: number of core threads
The minimum number of threads maintained by the thread pool. By default, core threads will not be recycled after they are created. (note: after allowCoreThreadTimeout=true is set, idle core threads will also be recycled beyond their survival time).
Threads larger than the number of core threads will be recycled after the idle time exceeds keepAliveTime.
MaximumPoolSize: maximum number of threads
The maximum number of threads allowed to be created by the thread pool.
When adding a task, the number of core threads is full, the thread pool has not reached the maximum number of threads, and there are no idle threads, and when the work queue is full, create a new thread, then take a task from the head of the work queue and hand it over to the new thread, and put the newly submitted task at the end of the work queue.
KeepAliveTime: idle thread survival time
When a recyclable thread has more idle time than keepAliveTime, it will be recycled.
Reclaimed thread:
Sets the core thread of the allowCoreThreadTimeout=true.
Threads that are greater than the number of core threads (non-core threads).
WorkQueue: work queu
After the new task is submitted, if the number of core threads is full, it will be added to the work queue first, and then the task will be removed from the queue when the task is scheduled. The work queue implements the BlockingQueue interface.
Handler: reject policy
When the number of thread pool threads is full and the work queue reaches the limit, the newly submitted task is processed using a reject strategy. You can customize the rejection policy, which requires the implementation of the RejectedExecutionHandler interface.
There are four default reject policies for JDK:
AbortPolicy: discards the task and throws a RejectedExecutionException exception.
DiscardPolicy: discards the task, but does not throw an exception. May cause the abnormal state of the system not to be discovered.
DiscardOldestPolicy: discard the first task in the queue and resubmit the rejected task.
CallerRunsPolicy: the task is handled by the calling thread.
The compiler issues a warning when we create a new thread using new Thread directly in a non-test file:
Do not explicitly create threads, use thread pools.
Note: the advantage of using thread pools is to reduce the time spent on creating and destroying threads and the overhead of system resources, and to solve the problem of insufficient resources. If the thread pool is not used, it may cause the system to create a large number of similar threads, resulting in running out of memory or "excessive switching".
Public class TestServiceImpl implements TestService {private final static Logger logger = LoggerFactory.getLogger (TestServiceImpl.class); @ Override public void task (int I) {logger.info ("task:" + I);} @ Autowired TestService testService; @ Test public void test () {for (int I = 0; I)
< 50; i++) { testService.task(i); } 我们可以看到一切执行正常;Then I did some tests on the thread:
Class TestServiceImplTest {@ Test public void test () {Thread add = new AddThread (); Thread dec = new DecThread (); add.start (); dec.start (); add.join (); dec.join (); System.out.println (Counter.count);} static class Counter {public static int count = 0;} class AddThread extends Thread {public void run () {for (int iTuno; I)
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.