Detailed Android thread pool Threadpoolexecutor Tutorial

Source: Internet
Author: User
Tags terminates

three ways to get a thread pool:

1. Executorservice pool = Executors.newfixedthreadpool
Create a thread pool that reuses the number of fixed threads to run them in a shared, unbounded queue. At any point, most nthreads threads are in the active state of the processing task. If additional tasks are committed when all threads are active, additional tasks will wait in the queue until there are available threads. If any thread terminates due to failure during execution prior to shutdown, a new thread will perform the subsequent task (if needed) instead. The threads in the pool will persist until a thread is explicitly closed.

2. Executorservice Pool = Executors.newsinglethreadexecutor
Create a Executor that uses a single worker thread to run the thread in a unbounded queue. (Note that if this individual thread is terminated because of a failure during execution prior to shutdown, a new thread will perform the successor task if needed). Each task is guaranteed to be performed sequentially, and no multiple threads are active at any given time. Unlike other equivalent Newfixedthreadpool (1), it is guaranteed that other threads can be used without reconfiguring the execution program returned by this method.

3. Executorservice Pool = Executors.newcachedthreadpool
Create a thread pool that can create new threads as needed, but reuse them when previously constructed threads are available. These thread pools generally improve program performance for programs that perform many short-term asynchronous tasks. Calling execute reuses the previously constructed thread (if the thread is available). If an existing thread is not available, create a new thread and add it to the pool. Terminates and removes threads from the cache that have not been used for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note that you can use the Threadpoolexecutor construct method to create a pool of threads with similar properties but with different details, such as time-out parameters.

second, thread pool class Java.util.concurrent.ThreadPoolExecutor explanation

Threadpoolexecutor (int corepoolsize, int maximumpoolsize,long keepalivetime, timeunit unit,blockingqueue, WorkQueue, Rejectedexecutionhandler handler)

parameter Description

Corepoolsize: Thread pool maintains minimum number of threads
Maximumpoolsize: Thread pool maintains maximum number of threads
KeepAliveTime: Thread pool maintains idle time allowed by threads
Unit: The units in which the thread pool maintains the idle time allowed by threads
Workqueue: Buffer queues used by the thread pool
Handler: thread pool processing policy for reject tasks

Thread Creation Rule

A task is added to the thread pool through the Execute (Runnable) method, and the task is a Runnable type object, and the task is performed by the Runnable type object's Run () method.
When a task is added to the thread pool through the Execute (Runnable) method:
L If the number of threads in the thread pool is less than corepoolsize, create a new thread to handle the added task even if the threads in the thread pool are idle.
2 If the number in the thread pool is equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is put into the buffer queue.
3 If the number of threads in the pool is greater than corepoolsize, the buffer queue is workqueue full, and the number of thread pools is less than maximumpoolsize, a new thread is built to handle the added task.
4 If the number of threads in the thread pool is greater than corepoolsize, the buffer queue is workqueue full, and the number in the thread pool equals maximumpoolsize, the task is handled through the policy specified by handler. That is: the priority of the processing task is: Core thread corepoolsize, Task queue workqueue, maximum thread maximumpoolsize, if all three are full, use handler to process the rejected task.
5 when the number of threads in the thread pool is greater than corepoolsize, the thread is terminated if a thread is idle longer than KeepAliveTime. This allows the thread pool to dynamically adjust the number of threads in the pool.

core and maximum pool size

Threadpoolexecutor automatically adjusts the pool size based on the boundaries set by Corepoolsize (see Getcorepoolsize ()) and maximumpoolsize (see Getmaximumpoolsize ()). When a new task is committed in method execute (java.lang.Runnable), if the running thread is less than corepoolsize, a new thread is created to process the request, even if the other worker threads are idle. If the thread running is more than corepoolsize and less than maximumpoolsize, the new thread is created only when the queue is full. If the corepoolsize and maximumpoolsize are set the same, a fixed size thread pool is created. If you set the Maximumpoolsize to a basic unbounded value, such as Integer.max_value, the pool is allowed to accommodate any number of concurrent tasks. In most cases, the core and maximum pool sizes are set only on a construction basis, but you can also use Setcorepoolsize (int) and setmaximumpoolsize (int) to make dynamic changes.

Create a new thread

Create a new thread using Threadfactory. If there is no additional description, the thread is created in the same threadgroup using Executors.defaultthreadfactory (), and these threads have the same norm_priority priority and non daemon state. By providing different threadfactory, you can change the name of the thread, the thread group, the priority, the daemon state, and so on. If threadfactory fails to create a thread when NULL is returned from Newthread, the executing program continues to run but cannot perform any tasks. If there are currently more than corepoolsize threads in the pool, these extra threads will terminate when idle time exceeds KeepAliveTime (see Getkeepalivetime (Java.util.concurrent.TimeUnit)). This provides a way to reduce resource consumption when the pool is inactive. If the pool later becomes more active, you can create a new thread. You can also use Method Setkeepalivetime (long, java.util.concurrent.TimeUnit) to dynamically change this parameter. The value using the Long.max_value timeunit.nanoseconds effectively disables the idle thread from the previous termination state before closing.

Line up

All blockingqueue can be used to transmit and maintain the submitted tasks. You can use this queue to interact with the pool size:
A. If the running thread is less than corepoolsize, Executor always prefers to add new threads without queuing.
B. If the thread that is running is equal to or greater than corepoolsize, Executor always prefers to join the queue without adding a new thread.
C. If the request cannot be joined to the queue, a new thread is created unless the thread is created beyond maximumpoolsize, in which case the task is rejected.

Execute () executes

In the Execute () method, three private methods are invoked
Addifundercorepoolsize (): The expansion thread pool is smaller than the core thread pool size
Addifundermaximumpoolsize (): When the online pool size is less than the maximum of the thread pool size, the expansion thread pool
Ensurequeuedtaskhandled (): To ensure that the thread pool is closed, new queued threads can also be handled correctly

stop and shutdown of the thread pool

Threadpoolexecutor provides two methods for the thread pool shutdown, respectively, shutdown () and Shutdownnow (), Where:
Shutdown (): Does not terminate the thread pool immediately, but waits until all tasks in the task cache queue have finished executing, but will never accept new tasks
Shutdownnow (): Terminates the thread pool immediately, attempts to interrupt the task being performed, and empties the task cache queue, returning tasks that have not yet been performed

Related Article

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.