Android four common thread pools

Source: Internet
Author: User

benefits of introducing a thread pool

1) Improve performance. Create and consume objects cost-consuming CPU resources

2) Prevent excessive memory consumption. Controls the number of active threads, preventing too many concurrent threads.

Let's take a look at the simple structure of a thread pool

Public threadpoolexecutor (int corepoolsize,                              int maximumpoolsize,                              long KeepAliveTime,                              timeunit Unit,                              Blockingqueue WorkQueue,                              Threadfactory threadfactory,                              Rejectedexecutionhandler handler) {...}
Using the above method to create the thread pool, we need to configure a bunch of things, very cumbersome, so we do not recommend this use.instead, the Executors factory method is recommended to create a thread pool, and the executors class is a factory class that is officially provided, which encapsulates a number of functionally different thread pools. Here are a few common thread pools.

Public Threadpoolexecutor (  //core thread count, unless Allowcorethreadtimeout is set to true, otherwise it will not die.  int Corepoolsize,   // The maximum number of threads, the number of active threads exceeds it, and subsequent tasks are queued                     int maximumpoolsize,   //Timeout length, Acting on a non-core thread (Allowcorethreadtimeout is set to true will also act on the core thread), idle timeout is recycled             long keepalivetime,                            //enum type, Set KeepAliveTime units, with Timeunit.milliseconds (MS), Timeunit. SECONDS (s) such as  timeunit Unit,  //Buffer task queue, the Execute method of the thread pool stores Runnable objects  blockingqueue<runnable> WorkQueue,  //Thread factory interface, there is only one new thread (Runnable R) method that can be created for the thread pool  threadfactory threadfactory)

1, Fixedthreadpool (): This method returns a thread pool with a fixed number of threads, the number of threads in the thread pool is always the same, that is, no new threads are created, and the threads that have been created are not destroyed, since all the fixed threads are working at the beginning. So the thread pool can control the maximum number of concurrent threads.
Chestnut: If there is a new task committed, if there is idle thread in the thread pool immediately use the idle thread to handle the task, if not, the new task will be present in a task queue, and once the threads are idle, the tasks in the task queue are processed in a FIFO manner.
public static Executorservice newfixthreadpool (int nthreads) {      return new Threadpoolexecutor (Nthreads, Nthreads, 0L , Timeunit.milliseconds, New linkedblockingqueue<runnable> ());  }  Use  Executors.newfixthreadpool (5). Execute (R);  


2, Cachedthreadpool ():
This method returns a thread pool that can adjust the number of threads in the thread pool according to the actual situation. That is, the number of threads in the thread pool is not deterministic and is dynamically adjusted according to the actual situation.
Chestnut: If all the threads in the thread pool are working, and a new task commits, then a new thread will be created to handle the task, and if some threads have completed the task and now have a new task committed, the new thread will not be created to handle the new task, but the idle thread should be reused to process it. So when someone has a question at this point, does that mean that the thread pool threads are more or less set? It does not, because threads in the thread pool have a "keep-active" parameter, and by configuring it, if the idle thread in the thread pool is idle longer than the "Save active Time", the thread is stopped immediately, and the pool's default "Keep-active time" is 60s.
public static Executorservice newcachedthreadpool (int nthreads) {      return new Threadpoolexecutor (0, Integer.max_ VALUE, 60L, Timeunit. SECONDS, New synchronousqueue<runnable> ());  }  Use  Executors.newcachedthreadpool (). Execute (R);  

3, Singlethreadexecutor (): This method returns a thread pool with only one threads, that is, only one thread task can be executed at a time, the extra task is saved to a task queue, waiting for this thread to be idle, When this thread is idle, the tasks in the task queue are then executed in FIFO order.
public static Executorservice newsinglethreadpool (int nthreads) {      return new Finalizabledelegatedexecutorservice ( New Threadpoolexecutor (1, 1, 0, Timeunit. MILLISECONDS, New Linkedblockingqueue<runnable> ()));  }  Use  

4, Scheduledthreadpool (): This method returns a thread pool that can control the threads of the thread pool to schedule or periodically perform a task.
public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize) {  return new Scheduledthreadpoolexecutor (corepoolsize);  }  Public scheduledthreadpoolexecutor (int corepoolsize) {  super (corepoolsize, Integer.max_value, 0, nanoseconds, new Delayedqueue ());  }  Use, delay 1 seconds, execute once every 2 seconds runnable R  



Custom thread pool common thread pool in Android in the above four, in fact, in Java there is a common thread pool (newsinglethreadscheduledexecutor), in fact, the above thread pool for our development is enough, But sometimes the above is still not enough for us, so we need to customize the thread pool of different functions. We also said that the thread pool function is different in the final analysis or internalBlockingqueueImplementation is different, so we have to implement our own thread pool, we must tamper with the implementation of Blockingqueue. Then we will then use Priorityblockingqueue to implement a FIFO thread pool.
1) Create a thread pool based on the Priorityblockingqueue
Executorservice Prioritythreadpool = new Threadpoolexecutor (3,3,0l,timeunit.seconds,new PriorityBlockingQueue ());

2) Create a class that implements the Runnable interface and provide us with the ability to implement custom functions and implement the comparable interface
Public abstract class Priorityrunnable implements Runnable, comparable {    private int priority;     Public priorityrunnable (int.) {        if (priority 0)            throw new IllegalArgumentException ();        This.priority = priority;    }     @Override public    int CompareTo (priorityrunnable another) {        int my = This.getpriority ();        int other = Another.getpriority ();        return my 1:my > other? -1:0;    }     @Override public    Void Run () {        dosth ();    }     public abstract void Dosth ();     public int getpriority () {        return to priority;    }}

3) Submit a task using priorityrunnable
Executorservice Prioritythreadpool = new Threadpoolexecutor (3, 3, 0L, Timeunit.seconds, New Priorityblockingqueue ()); c0/>for (int i = 1; i; i++) {            final int priority = i;            Prioritythreadpool.execute (new priorityrunnable) {@Override public                void Dosth () {                    String ThreadName = Thread.CurrentThread (). GetName ();                    LOG.V ("Zxy", "Thread:" + threadname + ", executing priority is:" + priorities + "task");                    try {                        thread.sleep;                    } catch (Interruptedexception e) {                        e.printstacktrace ();}}            );        }




Android four common thread pools

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.