In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to quickly understand Java thread pool". In daily operation, I believe many people have doubts about how to quickly understand Java thread pool. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to quickly understand Java thread pool"! Next, please follow the editor to study!
Lao Wang is a front-line programmer who works hard in Didu. He earns some money after a hard year and wants to deposit the money in a bank card. The money bank card management encounters the following experience.
After taking the number at the door of Lao Wang Bank, I found that there was a counter for business, but no one handled the business directly. After Lao Wang took the number, he found that someone was handling it at the counter, waiting for space at the table, so he went to sit and wait for it to be handled. After Lao Wang took the number, he found that the counter was handled and the waiting table was full. at this time, the bank manager saw that wheat was an honest man in an attitude of caring and caring for the honest man, and opened a new temporary window for him. After taking the number, Lao Wang found that the counters were full, the waiting seats were full, and the temporary window was also full. At this time, the bank manager gave a number of solutions. There are too many people to tell you directly that I won't handle it for you. When he saw Lao Wang, he got angry and didn't give it to him or let him go. The manager asked Lao Wang to try to talk to the front person in the seat to see if he could be plugged, he could handle it, but he couldn't be kicked out. The manager directly told Lao Wang who sent you. I can't handle it with whom you call.
The above process is almost similar to that of the JDK thread pool.
The three windows in business correspond to the number of core thread pools: the total number of business windows of corePoolSize Bank corresponds to: the temporary window opened by maximumPoolSize is closed when no one handles it: the waiting seat in unit Bank is the waiting queue: when workQueue cannot handle it, the bank gives the corresponding solution: RejectedExecutionHandlerthreadFactory this parameter is a thread factory in JDK, which is used to create thread objects and generally does not move.
The core workflow of the 5-minute thread pool has been explained. See below for more details.
What is a thread pool
The simple understanding is to create a certain number of thread objects in advance, store them in the buffer pool, take them out directly from the buffer pool when needed, do not destroy them after use, and return to the buffer pool.
Thread pool is necessary to improve the utilization of threads and reduce the consumption of resources. To improve the response speed, the thread creation time is T1, the execution time is T2, the destruction time is T3, and the time of T1 and T3 can be avoided with thread pool. It is convenient to manage thread objects in a unified way, and the maximum number of concurrency can be controlled manually.
How many important points can you consider if we let us manually implement a thread pool without looking at the thread pool source code?
There are several initialized thread arrays to act as thread pools. The thread pool goes to a waiting task queue to get the task.
To put it simply, initialize N threads to act as thread pools and then block take in the blocking queue together. All the newly added tasks append the task to the task queue through put. For an explanation of the task queue, see this blog.
Core class public class MyThreadPool2 {
/ / the number of default threads in the thread pool is 5
Private static int WORK_NUM = 5
/ / the default number of tasks in the queue is 100. There is no time to save the task.
Private static int TASK_COUNT = 100
/ / worker thread group
Private WorkThread [] workThreads
/ / Task queue as a buffer
Private final BlockingQueue taskQueue
/ / the number of threads that the user wants to start when constructing this pool
Private final int worker_num
/ / create a thread pool with default number of threads
Public MyThreadPool2 () {
This (WORK_NUM, TASK_COUNT)
}
/ / create a thread pool. Worker_num is the number of worker threads in the thread pool.
Public MyThreadPool2 (int worker_num, int taskCount) {
If (worker_num getPriceByS2 ())
/ / get the quotation of e-commerce S1 and save it
R=f1.get ()
Executor.execute (()-> save (r))
/ / get the quotation of e-commerce S2 and save it
R=f2.get ()
Executor.execute (()-> save (r))
The above solution itself is not a big problem, but there is one place you need to pay attention to, that is, if it takes a long time to get an e-commerce S1 quote, then even if it takes a short time to get an e-commerce S2 quote, you can't let the operation of saving the S2 quote be executed first, because the main thread is blocked in f1.get (), so how do we solve it? Solution: the results are stored in a blocking queue.
/ / create a blocking queue
BlockingQueue bq = new LinkedBlockingQueue ()
/ / the quotation of ecommerce S1 enters the congestion queue asynchronously
Executor.execute (()-> bq.put (f1.get ()
/ / E-commerce S2 quotes enter the congestion queue asynchronously
Executor.execute (()-> bq.put (f2.get ()
/ / Save all quotes asynchronously
For (int iTuno; isave (r))
}
Manual implementation of all the above work is not recommended in JDK8. JDK provides CompletionService, which also maintains a blocking queue internally, and its core function is to put the first tasks into the result set. When the task execution ends, the execution result of the task is added to the blocking queue, except that CompletionService adds the Future object of the task execution result to the blocking queue, while the above example code puts the final execution result of the task into the blocking queue. CompletionService combines the functions of Executor and BlockingQueue, and there is a blocking queue inside CompletionService. The implementation class of the CompletionService interface is ExecutorCompletionService. There are two constructors for this implementation class, which are:
ExecutorCompletionService (Executor executor)
ExecutorCompletionService (Executor executor, BlockingQueue completionQueue)
Both constructors need to pass in a thread pool, and if completionQueue is not specified, the unbounded LinkedBlockingQueue will be used by default. The Future object of the result of the task execution is added to the completionQueue.
/ / create a thread pool
ExecutorService executor = Executors.newFixedThreadPool (2)
/ / create a CompletionService
CompletionService cs = new ExecutorCompletionService (executor)
/ / Asynchronous inquiry to ecommerce S1
Cs.submit ()-> getPriceByS1 ()
/ / Asynchronous inquiry to ecommerce S2
Cs.submit ()-> getPriceByS2 ()
/ / asynchronously save the result of inquiry to the database
For (int iTuno; isave (r))
}
Let's make an overall demo to deepen our impression:
/ / Task class
Class WorkTask implements Callable
{
Private String name
Public WorkTask (String name)
{
This.name = name
}
@ Override
Public Integer call ()
{
Int sleepTime = new Random () .nextInt (1000)
Try
{
Thread.sleep (sleepTime)
} catch (InterruptedException e)
{
E.printStackTrace ()
}
Return sleepTime
}
}
Public class CompletionCase
{
Private final int POOL_SIZE = Runtime.getRuntime () .availableProcessors ()
Private final int TOTAL_TASK = Runtime.getRuntime () .availableProcessors ()
Public void selfByQueue () throws Exception
{
Long start = System.currentTimeMillis (); / / Statistics the total dormant time of all tasks
AtomicInteger count = new AtomicInteger (0)
ExecutorService pool = Executors.newFixedThreadPool (POOL_SIZE); / / create thread pool
BlockingQueue queue = new LinkedBlockingQueue (); / / the container stores tasks submitted to the thread pool, list,map
For (int I = 0; I < TOTAL_TASK; iTunes +)
{
Future future = pool.submit (new WorkTask ("tasks to be executed" + I))
Queue.add (future); / / iTun0 advanced queue, iTunes 1 tasks follow
}
For (int I = 0; I < TOTAL_TASK; iTunes +)
{
Int sleptTime = queue.take () .get (); / / check the thread pool task execution result iThread 0 get it first, then get it from iThread 1
System.out.println ("dormant milliseconds =" + sleptTime + "ms")
Count.addAndGet (sleptTime)
}
Pool.shutdown ()
System.out.println ("dormant time" + count.get () + "ms, elapsed time" + (System.currentTimeMillis ()-start) + "ms")
}
Public void testByCompletion () throws Exception
{
Long start = System.currentTimeMillis ()
AtomicInteger count = new AtomicInteger (0)
/ / create a thread pool
ExecutorService pool = Executors.newFixedThreadPool (POOL_SIZE)
CompletionService cService = new ExecutorCompletionService (pool)
/ / throw tasks into it
For (int I = 0; I < TOTAL_TASK; iTunes +)
{
CService.submit (new WorkTask (execute Task + I))
}
/ / check the execution result of thread pool task
For (int I = 0; I < TOTAL_TASK; iTunes +)
{
Int sleptTime = cService.take () .get ()
System.out.println ("dormant milliseconds =" + sleptTime + "ms...")
Count.addAndGet (sleptTime)
}
Pool.shutdown ()
System.out.println ("dormant time" + count.get () + "ms, elapsed time" + (System.currentTimeMillis ()-start) + "ms")
}
Public static void main (String [] args) throws Exception
{
CompletionCase t = new CompletionCase ()
T.selfByQueue ()
T.testByCompletion ()
}
}
Why do common exam questions use thread pool? What is the role of the thread pool? Commonly used thread pool templates? 7 important parameters? 4 rejection strategies? Common thread pool task queues, how to understand bounded and unbounded? 7. How to allocate the number of thread pools? Stand-alone thread pool implementation of the general power outage how to consider?
The transaction being processed is automatically rolled back the next time the queue is persisted and the next time automatic loading is started.
Set a thread pool priority queue, run class to achieve comparable function, task queue use priority queue here, on "how to quickly understand Java thread pool" learning is over, hope to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.