In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what is the use of thread pool in Java". The explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the use of thread pool in Java".
Thread pool in Java
[1] benefits of using thread pools:
1) reduce resource consumption and reduce the consumption caused by thread creation and destruction by reusing created threads. 2) improve the response speed so that when the task arrives, the task can be executed immediately without waiting for thread creation. 3) improve the manageability of threads. Thread pools can be uniformly allocated, tuned, and monitored.
[2] Construction method:
Public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler); parameter description: 1) corePoolSize: the size of the core pool. 1) after the thread pool is created, by default, there are no threads in the thread pool, but wait for a task to arrive before creating a thread to execute the task. 2) by default, after the thread pool is created, the number of threads in the thread pool is 0, and when a task comes, a thread is created to execute the task. Note: even if other idle threads are able to perform new tasks, threads will be created, and when the number of threads in the thread pool reaches corePoolSize, the incoming tasks will be placed in the cache queue. 3) call the prestartAllCoreThreads () or prestartCoreThread () method to pre-create a thread, that is, create a corePoolSize thread or a thread before no task arrives. 2) workQueue: task cache queue, which is a blocking queue used to store tasks waiting for execution. The type is BlockingQueue. You can usually take the following four types: 1) ArrayBlockingQueue: array-based FIFO queue, which must be created with a specified size. 2) LinkedBlockingQueue: a linked list-based first-in-first-out queue. If the queue size is not specified at the time of creation, the default is Integer.MAX_VALUE, and the throughput is usually higher than ArrayBlockingQueue. Eg: this queue is used by the static factory method Executors.newFixedThreadPool (). 3) SynchronousQueue: this queue does not save the submitted task, but directly creates a new thread to execute the new task. Note: each insert operation must wait until another thread calls the remove operation, otherwise the insert operation will always be blocked and the throughput is usually higher than that of LinkedBlockingQueue. Eg: this is the queue used by the static factory method Executors.newCachedThreadPool. 4) PriorityBlockingQueue: an infinite blocking queue with priority. Note: 1 > generally use LinkedBlockingQueue and SynchronousQueue 2 > it is recommended to use bounded queues, which can increase the stability of the system. Eg: if all the worker threads in the thread pool are blocked and the tasks are overstocked in the thread pool, if the queue is set to an unbounded queue, the queue will become larger and larger, which may fill up memory and make the whole system unavailable. 3) maximumPoolSize: the maximum number of threads allowed to be created in the thread pool. 1) 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. 2) if an unbounded task queue is used, this parameter will not work (the default size of the queue is: Integer.MAX_VALUE, the thread pool will not create new threads until the queue is full). 4) RejectedExecutionHandler: task rejection policy. When the task cache queue is full and the number of threads in the thread pool reaches maximumPoolSize, a task rejection policy will be adopted if another task arrives. There are usually the following four strategies: 1) ThreadPoolExecutor.AbortPolicy: discard the task and throw a RejectedExecutionException exception. This policy is used by default. 2) ThreadPoolExecutor.DiscardPolicy: discards the task, but does not throw an exception; it will cause the discarded task to not be executed again; 3) ThreadPoolExecutor.DiscardOldestPolicy: discard the task at the top of the queue and then try to execute the task again (repeat this process); it will cause the discarded task to not be executed again 4) ThreadPoolExecutor.CallerRunsPolicy: the task will be handled by the calling thread The main thread executes the task directly, and then tries to add the next task to the thread pool, which can effectively reduce the speed of adding tasks to the thread pool. Description: you can also implement the RejectedExecutionHandler API to customize policies. 5) keepAliveTime: indicates how long a thread will be terminated when there is no task to execute. By default, keepAliveTime works only if the number of threads in the thread pool is greater than corePoolSize. But if the allowCoreThreadTimeOut (boolean) method is called, and the number of threads in the thread pool is not greater than corePoolSize, the keepAliveTime parameter will also work until the number of threads in the thread pool is 0 6) TimeUnit: the time unit of the parameter keepAliveTime, which has 7 values. There are 7 static attributes in the TimeUnit class: TimeUnit.DAYS; day TimeUnit.HOURS; hour TimeUnit.MINUTES Minutes TimeUnit.SECONDS; seconds TimeUnit.MILLISECONDS; milliseconds TimeUnit.MICROSECONDS; subtle TimeUnit.NANOSECONDS Nanosecond 7) ThreadFactory: used to set the factory that creates threads, you can use the thread factory to give each created thread a more meaningful name.
[3] other methods:
Task submission: execute (Runnable command): there is no return value after submission, so it is impossible to determine whether the task was successfully executed by the thread pool. Submit (): returns a Future object after submission, which can be used to determine whether the task was executed successfully or not. The return value is obtained through the get () method of future, which blocks the current thread until the task is complete. Get (long timeout, TimeUnit unit) method: returns immediately after blocking the current thread for a period of time, when the task may not be finished. Dynamic adjustment of thread pool capacity: setCorePoolSize () sets the size of the core pool setMaximumPoolSize () sets the maximum number of threads that can be created in the thread pool: principle: traverse the worker threads in the thread pool, and then call the thread's interrupt method one by one to interrupt the thread, so tasks that cannot respond to interruptions may never be terminated. Shutdown () 1 > sets the state of the thread pool to SHUTDOWN, and then interrupts all threads that are not performing tasks. 2 > New tasks are no longer accepted, but the thread pool is not terminated immediately, but not until all tasks in the task cache queue have been executed. ShutdownNow () 1 > first sets the state of the thread pool to STOP, then attempts to stop all threads that are executing or pausing tasks, clears the task cache queue, and returns the list of tasks waiting to be executed. Note: 1) as long as either of these two close methods is called, the isShutdown method will return true. 2) when all tasks have been closed, the thread pool is closed successfully. Calling the isTerminaed method returns true.
[4] status of thread pool:
/ / RUNNING status: thread pool is running normally. You can accept new tasks and process tasks in the queue private static final int RUNNING =-1
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.