Java Interview Classic topic: Thread pool Topic

Source: Internet
Author: User
Tags throw exception

1. What is a thread pool

The basic idea of thread pool is a kind of object pool, which opens up a memory space when the program starts, it holds many (not dead) threads, and the pool thread execution schedule is handled by the pool manager. When a thread task is taken from a pool, the threads object is pooled after execution, which avoids the performance overhead of repeatedly creating thread objects and saves system resources.

2. Benefits of using the thread pool
  1. Reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks.
  2. The use of thread pool can effectively control the maximum number of threads, can be based on the capacity of the system to adjust the number of threads in the thread pool, to prevent excessive memory consumption, and the server tired of the ground (each thread needs about 1MB of memory, the more threads open, the more memory consumed, the last panic).
  3. Some simple management of the thread, such as: Delay execution, timing loop execution strategy, the use of thread pool can be very good implementation
3. Main components of the thread pool

A thread pool consists of the following four basic components:

    1. Thread pool Manager (ThreadPool): Used to create and manage thread pools, including creating a thread pool, destroying the thread pool, adding new tasks;
    2. Worker thread (workthread): Thread pool threads, in the absence of a task in the waiting state, you can cycle the execution of tasks;
    3. Task Interfaces (tasks): Each task must implement an interface for the execution of task scheduling tasks, it mainly specifies the entry of the task, the completion of the task after the end of the task, the status of the implementation of tasks;
    4. Task Queue (Taskqueue): Used to hold tasks that are not processed. Provides a buffering mechanism.
4, Threadpoolexecutor class

Talking about the thread pool, To focus on the Java.uitl.concurrent.ThreadPoolExecutor class, Threadpoolexecutor a class in the core of the thread pool, threadpoolexecutor the Common class UML class diagram in the JDK Center pool is as follows:

We can create a thread pool through threadpoolexecutor.

new ThreadPoolExecutor(corePoolSize, maximumPoolSize,keepAliveTime, milliseconds,runnableTaskQueue, threadFactory,handler);复制代码
1. Create a thread pool you need to enter a few parameters
    • corepoolsize (basic size of the thread pool): When a task is submitted to the thread pool, the thread pool creates a thread to perform the task, even if other idle basic threads are able to perform new tasks, Wait until the number of tasks that need to be executed is greater than the thread pool base size. If the thread pool's Prestartallcorethreads method 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 a thread pool. If the queue is full and the number of threads that have been created is less than the maximum number of threads, the thread pool will then create new threads to perform the task. It is worth noting that if you use the unbounded task queue This parameter has little effect.
    • runnabletaskqueue (Task queue): A blocking queue that is used to hold tasks waiting to be executed.
    • threadfactory: Used to set the factory for creating threads, you can set a more meaningful name for each thread that is created through the thread factory, and it is very helpful to debug and locate problems.
    • Rejectedexecutionhandler (Deny policy): When the queue and thread pool are full, indicating that the thread pools are saturated, a policy must be taken to handle the new tasks that are submitted. This policy is abortpolicy by default, indicating that an exception is thrown when a new task cannot be processed. The following are the four strategies provided by JDK1.5. N AbortPolicy: Throws an exception directly.
    • KeepAliveTime (thread activity hold time): When the worker thread of the thread pool is idle, the time to remain alive. So if the task is a lot, and each task executes a short time, you can adjust the time to increase the utilization of the thread.
    • timeunit (unit of thread activity hold time): Optional unit with day (days), hours (HOURS), minutes (MINUTES), milliseconds (MILLISECONDS), microseconds (microseconds, 1 per thousand ms) and nanoseconds (nanoseconds, 1 per thousand microseconds).
2. Submit a task to the thread pool

We can submit a task to the thread pool through execute () or submit () two methods, but they are different

    • The Execute () method does not return a value, so it is not possible to determine whether the task is successfully executed by the thread pool
Runnable() {    @Override    public void run() {    // TODO Auto-generated method stub   }});复制代码
    • The Submit () method returns a future, so we can use this future to determine if the task is successful, and get the return value through the Get method of the future
try {     Object s = future.get();   } catch (InterruptedException e) {   // 处理中断异常   } catch (ExecutionException e) {   // 处理无法执行任务异常   } finally {   // 关闭线程池   executor.shutdown();}复制代码
3. Shutdown of the thread pool

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

    • The principle of shutdown is simply to set the state of the thread pool to shutdown state, and then break all threads that are not performing the task.
    • 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, so that a task that cannot respond to the interrupt may never be terminated. Shutdownnow first sets the status of the thread pool to stop, and then tries to stop all threads that are executing or pausing the task, and returns a list of waiting tasks to be performed.
4. Threadpoolexecutor Execution Strategy

    1. A new thread (core thread) performs a task when the number of threads does not reach corepoolsize
    2. When the number of threads reaches Corepools, the task is moved into the queue waiting
    3. Queue is full, new thread (non-core thread) performs task
    4. When the queue is full and the number of bus threads reaches Maximumpoolsize, an exception is thrown by (Rejectedexecutionhandler)

New thread-to-core number, join queue, new thread (non-core), maximum number-up trigger deny policy

5. Four rejection strategies
    1. AbortPolicy: Do not perform new task, throw exception directly, prompt thread pool is full, thread pool default policy
    2. Discardpolicy: Do not perform new tasks or throw exceptions, basically silent mode.
    3. Discardoldsetpolicy: Replaces the first task in Message Queuing with the current new incoming task execution
    4. Callerrunpolicy: Deny new Task entry, if the thread pool has not been closed, then this new task is called in the execution thread
5, Java provides four kinds of thread pool through executors
  1. Cachedthreadpool (): The thread pool can be cached.
    • Unlimited number of threads
    • There are idle threads that reuse the idle thread, and if there is no idle thread, the new thread must reduce the frequent creation/destruction of threads, reducing system overhead
  1. Fixedthreadpool (): Fixed thread pool.
    • Can control the maximum number of concurrent threads (number of threads executing concurrently)
    • The exceeded thread waits in the queue
  1. Scheduledthreadpool ():
    • Timed thread pool.
    • Support timed and recurring task execution.
  1. Singlethreadexecutor (): Single threaded thread pool.
    • There is only one worker thread that performs the task
    • All tasks are executed in the specified order, that is, following the queued rules of the queue
1. Newcachedthreadpool

Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and if it is not recyclable, the new thread

public class ThreadPoolExecutorTest1 {public static void main(String[] args) {ExecutorService cachedThreadPool = Executors.newCachedThreadPool();for (int i = 0; i < 1000; i++) {final int index = i;try {Thread.sleep(index * 1000);} catch (Exception e) {e.printStackTrace();}cachedThreadPool.execute(new Runnable() {public void run() {System.out.println(Thread.currentThread().getName()+":"+index);}});}}}复制代码

2. Newfixedthreadpool

Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue, specifying the number of threads in the thread pool and the maximum number of threads, as well as fixing the number of threads

The sample code is as follows

public class ThreadPoolExecutorTest {public static void main(String[] args) {ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);// 每隔两秒打印3个数for (int i = 0; i < 10; i++) {final int index = i;fixedThreadPool.execute(new Runnable() {public void run() {try {System.out.println(Thread.currentThread().getName()+":"+index);//三个线程并发Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}});}}}复制代码

3. Newscheduledthreadpool

Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution. The deferred execution example code is as follows. Represents a delay of 1 seconds after every 3 seconds

Runnable() {public void run() {System.out.println(Thread.currentThread().getName() + ": delay 1 seconds, and excute every 3 seconds");}}, 1, 3, TimeUnit.SECONDS);// 表示延迟1秒后每3秒执行一次}}复制代码

4. Newsinglethreadexecutor

Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority)

public class ThreadPoolExecutorTest4 {public static void main(String[] args) {ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();for (int i = 0; i < 10; i++) {final int index = i;singleThreadExecutor.execute(new Runnable() {public void run() {try {System.out.println(Thread.currentThread().getName() + ":" + index);Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}});}}}复制代码

The results are output sequentially, which is equivalent to performing each task sequentially. Monitor the number of threads we create using the JDK's own monitoring tools, run a non-terminating thread, create a specified amount of threads, and observe



Java Interview Classic topic: Thread pool Topic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.