How the thread pool works and uses examples

Source: Internet
Author: User

. Why use a thread pool?

We now consider the simplest server working model: The server creates a thread for its service whenever a client request is received. This mode works well in theory, but there are some drawbacks, and it is common in server applications that the task of single client request processing is simple but the number of clients is huge. Therefore, the time and system resources that the server spends creating and destroying threads can be more time and resources than the task of processing client requests.

Thread pooling techniques are designed to solve these problems. A reasonable use of the thread pool allows you to reuse the threads you have created to reduce the time and resources spent on creating threads and destroying threads. In addition, the thread pool can dynamically adjust the number of worker threads in some cases to balance resource consumption and productivity. The thread pool also provides methods for unified management of worker threads in the pool.

2. A brief working model of the thread pool

The working model of the thread pool consists of two main parts: The thread object that runs Runnable, and the other is the blocking queue.

The thread object created by the thread pool its internal run method obtains a Runnable object by blocking the take method of the queue, and then executes the run method of the Runnable object (that is, Call the Run method of the Runnable object in the thread's Run method). When the Run method of the Runnable object finishes executing, the Run method in thread loops through the blocking queue to get the next Runnable object to continue execution. This enables the reuse of thread objects and reduces the resources consumed by creating threads and destroying threads.

When a task needs to be submitted to the thread pool, the offer method of the blocking queue is called to add a task to the tail of the queue. The task being submitted is actually a Runnable object or callable object.

The above is only the most abbreviated thread pool work model, but embodies the core idea of thread pool, and as for the threads of threading pools in the dynamic creation and self-destruction, dynamically adjust the actual number of working threads, blocking queue policy, queue length and so on the details of this blog "thread pool Threadpoolexecutor, executors source code Analysis "in the article detailed description.

3. Relations between Executor, Executorservice, Abstractexecutorservice, Threadpoolexecutor and executors

As you can see, the Executorservice interface defines the behavior characteristics that the thread pool should have (not all of the Executorsservice methods are listed in the figure), and the Threadpoolexecutor class is the real implementation of the thread pool. Because Threadpoolexecutor has a large number of constructor parameters and some parameters can have a significant impact on the work of the thread. In order to prevent the user from mistakenly collocation the parameters of the Threadpoolexecutor constructor and the more convenient and concise creation of the Threadpoolexecutor object, executors class is defined in Javase. The Eexcutors class provides a way to create a common configuration thread pool.

4. Executorservice Interface Introduction

The Executorservice interface defines the behavior characteristics that the thread pool should have, and it has the following main methods

123456789101112 voidshutdown();List<Runnable> shutdownNow();booleanisTerminated();<T> Future<T> submit(Callable<T> task);Future<?> submit(Runnable task);<T> List<Future<T>> invokeAll(Collection<? extendsCallable<T>> tasks)    throwsInterruptedException;<T> T invokeAny(Collection<? extendsCallable<T>> tasks)    throwsInterruptedException, ExecutionException;

Submit Related methods: Add a task to the thread pool to perform

shutdown Method: This method does not submit the task to the thread pool again, if there is an idle thread, destroys the idle thread, waits for all the executing tasks and the execution of the task in the blocking queue to end, and then destroys all the threads.

Shutdownnow Method: This method does not submit the task to the thread pool again, if there is an idle thread destroys the idle thread, cancels all the tasks that are in the blocking queue, and puts it in the List<runnable> container as the return value. Cancels the executing thread (actually just setting the interrupt flag bit of the executing thread).

InvokeAll Method: Submits multiple tasks to the thread pool at once, and returns all results.

Invokeany Method: Once multiple tasks are submitted to the thread pool, the first result is returned as a return value, and all executing threads are immediately canceled.

isterminated Method: After all the threads in the pool are destroyed, the method returns True, otherwise false is returned.

Because Executorservice inherits the executor interface, it actually has an Execute method, which functions as a task of submitting a Runnable object to the thread pool. The Execute method is called in the Submit method, but submit submits the Runnable object or callable object to the Runnablefuture object before invoking the Execute method, and then to execute to submit the task.

5. Thread Pool Usage Example
Package javalearning; Import Java.util.random;import Java.util.concurrent.executorservice;import java.util.concurrent.Executors;        public class ThreadPoolDemo {static Class Task implements runnable{private String ID;        Task (String id) {this.id = ID;             } @Override public void Run () {System.out.println ("Thread" +id+ "is working");            try {//each task is randomly delayed within 1s to simulate the running thread.sleep of the thread (new random (). Nextint (1000));            } catch (Interruptedexception e) {e.printstacktrace ();        } System.out.println ("Thread" +id+ "over"); }} public static void Main (string[] args) {Executorservice ThreadPool = Executors.newfixedthreadpool (3        );//thread pool, 3 worker thread Threadpool.execute (new Task ("a"));        Threadpool.execute (New Task ("B"));        Threadpool.execute (New Task ("C"));        Threadpool.execute (New Task ("D")); Threadpool.execute (New TAsk ("E"));        Threadpool.shutdown ();    while (!threadpool.isterminated ()) {} System.out.println ("Thread Pool was over"); }}

As you can see from the execution results, there are up to three threads concurrently executing, and after more than three tasks, the thread pool stores the tasks in the blocking queue.

 is areis Over

How the thread pool works and uses examples

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.