Android Thread pool Depth analysis

Source: Internet
Author: User

1. Introduction of Thread pool

Benefits of Introduction:
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.
Conditions of Use:
Assume that the time to complete a task on a single server is T
T1 when the thread was created
T2 time to execute a task in a thread, including the time required to synchronize between threads
T3 the time the thread was destroyed
Obviously t = t1+t2+t3. Note that this is an extremely simplified hypothesis.
It can be seen that T1,T3 is the overhead of multithreading itself, and we are eager to reduce the time it takes to t1,t3, thus reducing t time. However, users of some threads do not notice this, so the threads are created or destroyed frequently in the program, which causes T1 and T3 to occupy a considerable proportion in T. Obviously this is the highlight of the thread's weakness (T1,T3), not the merit (concurrency).
Thread pooling technology is a technique that focuses on how to shorten or adjust t1,t3 time to improve the performance of server programs. It t1,t3 the start and end of the server program, or some idle time period, so that there is no t1,t3 overhead when the server program processes the client request.
The thread pool not only adjusts the time period generated by the T1,T3, but it also significantly reduces the number of threads created.

In Android, the introduction of thread pooling technology can greatly improve the performance of your app when concurrent with multiple network threads.

2. Thread Pool Example
1) The JDK itself has a thread pool implementation class Threadpoolexecutor
2) Here is an example of a simulated threadpoolexecutor to deepen the understanding of the principle

Public final class ThreadPool {//The number of default threads in the thread pool is 5 private static int worker_num = 5;         Worker thread private workthread[] workthreads;     Task queue, as a buffer, List thread unsafe private list<runnable> taskqueue = new linkedlist<runnable> ();     private static ThreadPool ThreadPool;     Creates a thread pool with a default number of threads private ThreadPool () {this (5); }//Create thread pool, worker_num as the number of worker threads in thread pooling private ThreadPool (int worker_num) {threadpool.worker_num = Worker_num          ;          Workthreads = new Workthread[worker_num];               for (int i = 0; i < Worker_num; i++) {workthreads[i] = new Workthread (); Workthreads[i].start ();//Open threads in thread pool}}//single-state mode, get a thread pool with default number of threads public static ThreadPool Getthreadpool     () {return getthreadpool (threadpool.worker_num);  }//single-state mode, get a thread pool with a specified number of threads, Worker_num (>0) creates the default number of worker threads for the number of worker threads in the thread pools//worker_num<=0 public static ThreadPool    Getthreadpool (int worker_num1) {      if (ThreadPool = = null) ThreadPool = new ThreadPool (WORKER_NUM1);     return threadPool;               }//Perform a task, actually just put the task into the task queue, when to execute the thread pool manager public void AddTask (Runnable Task) {synchronized (taskqueue) {               Taskqueue.add (Task); Taskqueue.          Notifyall (); }//destroys the thread pool, which ensures that all threads are destroyed if all tasks are completed, otherwise the public void destroy () {while (!taskqueue.isempty ()} is not destroyed until the task is completed               {//If there is still a task to complete, go to sleep. try {thread.sleep (10);               } catch (Interruptedexception e) {e.printstacktrace (); }}//worker stopped working with NULL for (int i = 0; i < Worker_num; i++) {workthreads[i].               Stopworker ();          Workthreads[i] = null;          } threadpool=null; Taskqueue.clear ();//Empty task queue}/** * Inner class, worker thread */private class Workthread extends thread {/ /Whether the worker thread is valid to end the worker thread PRivate Boolean isrunning = true;               /* Key, if the task queue is not empty, then the task execution is removed, if the task queue is empty, wait */@Override public void run () {               Runnable r = null; while (isrunning) {//Note that if the thread is not valid, the Run method ends naturally, and the thread is useless synchronized (taskqueue) {WHI                                   Le (isrunning && taskqueue.isempty ()) {//queue is empty try {                              Taskqueue.wait (20);                              } catch (Interruptedexception e) {e.printstacktrace (); }} if (!taskqueue.isempty ()) R = TASKQUEUE.R                    emove (0);//Remove Task} if (r! = null) {R.run ();//Perform task               } r = null;  }}//stop working so that the thread naturally finishes executing the Run method and ends naturally with the public void Stopworker () {             IsRunning = false; }     }}

Thread pool depth profiling for Android

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.