When we need to download resources in the ListView, like regardless of the caching mechanism, then each item may need to open a thread to download resources (if there is no thread pool), if the item is many, then we will be unlimited to create a new thread to perform the download task, the end result may be caused, Application lag, mobile phone unresponsive! The worst result is that the user uninstalls the app directly. Therefore, we need to consider multi-threading in the actual development, multithreading is inseparable from the thread pool. If you don't know the thread yet, you can look at this article, Android (thread one) thread.
Advantages of using the thread pool:
(1). Reuse threads to avoid the performance overhead associated with creating and destroying threads;
(2). Can effectively control the maximum concurrency of the thread pool, avoid a large number of threads due to each other to seize the system resources caused by blocking phenomenon;
(3). Ability to easily manage threads and provide functions such as timed execution and specified interval loop execution.
The thread pool in Android is from Java. Then you need to look at the thread pool in Java. There are four thread pools in Java:
(1). Singlethreadexecutor, 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);
(2). Cachedthreadpool, create a cacheable thread pool, if the thread pool length exceeds the processing need, can flexibly reclaim the idle thread, if not recyclable, the new thread;
(3). Fixedthreadpool, a thread pool is created to control the maximum number of concurrent threads, and the excess threads wait in the queue;
(4). Scheduledthreadpool, create a fixed-line pool that supports timed and recurring task execution.
PS: Create a thread pool, using the Executors class. This class enables you to obtain instances of multiple thread pools. Executors's core construction Method Threadpoolexecutor (), Next, let's take a look at the method description,
Threadpoolexecutor (int corepoolsize,int maximumpoolsize,long keepalivetime, timeunit unit, BlockingQueue<Runnable > WorkQueue, threadfactory threadfactory,rejectedexecutionhandler handler)
Parameter description:
The corepoolsize thread pool maintains the minimum number of threads (the number of core threads), and by default, the core threads will survive in the inline pool even if they are idle. If you set the Allowcorethreadtimeout property of Threadpoolexecutor to True, the idle core thread will have a supermarket policy waiting for the new task to arrive, and this interval is specified by KeepAliveTime. When the wait time exceeds the length specified by KeepAliveTime, the core thread is terminated.
The maximumpoolsize thread pool maintains the maximum number of threads, and when the active thread reaches this value, subsequent newcomers will be blocked.
KeepAliveTime The maximum number of idle threads in a thread pool that exceeds corepoolsize, and can be allowcorethreadtimeout (true) to make the core thread valid for time.
Unit KeepAliveTime Time Unit, there are 7 kinds of values, there are 7 kinds of static properties in the Timeunit class:
Timeunit.days; Days Timeunit.hours; Hour timeunit.minutes; Minutes Timeunit.seconds; Seconds timeunit.milliseconds; Ms Timeunit.microseconds; Subtle timeunit.nanoseconds; Na-Sec
workQueue thread pool, The Runnable object that is submitted through the thread pool's Execute method is stored in this parameter.
threadfactory new Thread factory, providing the thread pool with the ability to create new threads, Threadfactory is an interface with only one method: Thread Newthread (Runnable R).
handler When the number of submitted tasks exceeds the sum of Maxmumpoolsize+workqueue, the task is assigned to Rejectedexecutionhandler;
The relationship between Corepoolsize,maximumpoolsize,workqueue, as described below,
(1). When the thread pool is smaller than corepoolsize, the new commit task creates a new thread to perform the task. Even if there are idle threads in the thread pool at this time;
(2). When the thread pool reaches corepoolsize, the new commit task is put into Workqueue, waiting for the task to be dispatched in the thread pool;
(3). When Workqueue is full and maximumpoolsize>corepoolsize, the new commit task creates a new thread to perform the task;
(4). When the number of submitted tasks exceeds maximumpoolsize, the new submission is handled by Rejectedexecutionhandler;
(5). When the thread pool exceeds the corepoolsize thread and the idle time reaches KeepAliveTime, the idle thread is closed;
(6). When Allowcorethreadtimeout (true) is set, the corepoolsize thread idle time in the thread pool reaches KeepAliveTime will also close.
1.SingleThreadExecutor.
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 single thread is terminated because of a failure during the execution of the shutdown, a new thread will replace it for subsequent tasks if needed). Each task is guaranteed to be executed sequentially, and no more than one thread is active at any given time. Then look at the Newsinglethreadexecutor source code implementation,
public static Executorservice Newsinglethreadexecutor () { return new Finalizabledelegatedexecutorservice ( New Threadpoolexecutor (1, 1, 0L, Timeunit.milliseconds, new Linkedblockingqueue<runnable> ())); }
Constructs a thread pool that supports only one threads, configures corepoolsize=maximumpoolsize=1, unbounded blocking queue linkedblockingqueue, and ensures that tasks are executed serially by one thread. Example code:
public static void Singthreadexecutors () {Executorservice pool = executors.newsinglethreadexecutor ();// Create an object that implements the Runnable interface thread T1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread ();//place thread into pool for execution pool.execute (t1);p ool.execute (T2);p Ool.execute (T3);p ool.execute (T4); Pool.execute (T5);//close thread pool Pool.shutdown ();}
Class MyThread extends Thread {@Overridepublic void run () {try {System.out.println (Thread.CurrentThread (). GetName () + " is running ... "); Thread.Sleep (2000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Print once every 2 seconds. The result is output sequentially, which is equivalent to executing each task in sequence, running:
most of the current GUI programs are single-threaded. Single-threaded Android can be used for database operations, file operations, application batch installation, application bulk deletion, etc. that are not suitable for concurrency but may have IO blocking and affect UI thread response actions.
There is only one core thread inside this type of thread pool, which ensures that all tasks are executed sequentially in the same thread. The point of Singlethreadexecutor is to unify all outside tasks into one thread, which makes it unnecessary to handle thread synchronization between these tasks.
2.CachedThreadPool.
Executorservice pool = Executors.newcachedthreadpool ();
creates a cacheable pool of threads. If the size of the thread pool exceeds the thread required to process the task, then a partially idle (60 second non-performing task) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create. Then look at the Newcachedthreadpool source code implementation,
public static Executorservice Newcachedthreadpool () { return new Threadpoolexecutor (0, Integer.max_value, 60L , Timeunit.seconds, new synchronousqueue<runnable> ()); }
The core thread is 0, the maximum number of threads is 231-1, the thread KeepAliveTime is 60, the unit is seconds, and the cache queue is the synchronousqueue thread pool, because multiple threads share a synchronousqueue, Therefore, it is necessary to ensure that each thread's access to the Synchronousqueue is serial, that is, the previous thread is not finished, and the latter thread must wait to ensure the integrity of the Synchronousqueue internal data. Example code:
public static void Cachedthreadpool () {Executorservice pool = Executors.newcachedthreadpool ();// Create an object that implements the Runnable interface thread T1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread ();//place thread into pool for execution pool.execute (t1);p ool.execute (T2);p Ool.execute (T3);p ool.execute (T4); Pool.execute (T5);//close thread pool Pool.shutdown ();}
5 threads were created to perform different tasks, running:
It is a thread pool with a variable number of threads, with only non-core threads and a maximum of 231-1 threads. Since 231-1 is a large number, it is actually equivalent to the maximum number of threads that can be arbitrarily large. When a thread in the thread pool is active, the line pool creates a new thread to handle the new task, or the idle thread is used to process the new task. Idle threads in the thread pool have a time-out mechanism, which is 60 seconds long and idle threads are recycled for more than 60 seconds. Unlike Fixedthreadpool, Cachedthreadpool's task queue is actually equivalent to an empty collection, which will cause any task to be executed immediately, because in this scenario Synchronousqueue cannot insert the task. This type of thread pool is better suited to perform a large number of less time-consuming tasks. When the entire thread pool is idle, threads in the thread pools are timed out, and at this point the Cachedthreadpool is virtually free of any threads, and it almost does not occupy any system resources.
3.FixedThreadPool.
Executorservice pool = executors.newfixedthreadpool (int nthreads);
Create a thread pool that can reuse a fixed number of threads, nthreads=3 the thread pool that created 3 threads (the size of the thread pool is best based on system resources), and then look at the Newfixedthreadpool source implementation,
public static Executorservice newfixedthreadpool (int nthreads) { return new Threadpoolexecutor (Nthreads, Nthreads, 0L, Timeunit.milliseconds, new linkedblockingqueue<runnable> ()); }
The size of the corepoolsize and Maximumpoolsize is the same, it is set according to the parameters passed, KeepAliveTime is 0, that does not want to keep alive. Example code:
public static void Fixedthreadpool () {Executorservice pool = Executors.newfixedthreadpool (3);// Create an object that implements the Runnable interface thread T1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread ();//place thread into pool for execution pool.execute (t1);p ool.execute (T2);p Ool.execute (T3);p ool.execute (T4); Pool.execute (T5);//close thread pool Pool.shutdown ();}
The thread pool has a fixed number of threads of 3, first creating 3 threads to execute, then the idle state after execution, and then other wait tasks to run:
It is a thread pool with a fixed number of threads that are not recycled when the threads are idle, unless the thread pool is closed. When all the threads are active, the new task waits until the thread is idle. Since Fixedthreadpool has only core threads and these core threads are not recycled, this means that it can respond more quickly to outside requests.
4.ScheduledThreadPool.
Scheduledexecutorservice pool = executors.newscheduledthreadpool (int corepoolsize)
then look at the source code of Newscheduledthreadpool,
public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize) { return new Scheduledthreadpoolexecutor (corepoolsize); }
Public scheduledthreadpoolexecutor (int corepoolsize) { super (corepoolsize, Integer.max_value, default_ Keepalive_millis, MILLISECONDS, new Delayedworkqueue ()); }
The source code for super (Corepoolsize, Integer.max_value,default_keepalive_millis, MILLISECONDS, New Delayedworkqueue ()) is the following, which is still called threadpoolexecutor to create a thread pool,
Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, long KeepAliveTime, timeunit Unit, blockingqueue<runnable> WorkQueue) {This (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, executors.defaultthreadfactory (), DefaultHandler); }
Each scheduled task is executed by a thread in the thread pool, so the tasks are executed concurrently and are not interfered with each other. It is important to note that only when the execution time of a task arrives does scheduedexecutor actually start a thread, and the rest of the time Scheduledexecutor is the state of the polling task.
Example code:
Scheduledexecutorservice Scheduledexecutorservice=executors.newscheduledthreadpool (4); Execute command scheduledexecutorservice.schedule (command,2000,timeunit.milliseconds) after 2000ms; After 10ms delay, command Scheduledexecutorservice.scheduleatfixedrate (command,10,1000,timeunit.milliseconds) is executed every 1000ms;
its core thread data is fixed, not the number of core threads, and is immediately recycled when non-core threads are restricted. Scheduledthreadpool such thread pools are primarily used to perform scheduled tasks and repetitive tasks with fixed cycles.
Summarize:
(1). The maximum number of threads is generally set to 2n+1 best, N is the number of CPU cores;
(2). Read the Asynctask source of the students will know, in fact, its internal is a thread pool;
(3). When the thread pool is created, at the initial time, it is in the running state;
(4). If the shutdown () method is called, then the thread pool is in the shutdown state, and it is not able to accept the new task, and it waits for all tasks to complete;
(5). If the Shutdownnow () method is called, then the thread pool is in the stop state, at which point it is unable to accept the new task and will attempt to terminate the task being performed;
(6). When the thread pool is in the shutdown or stop state, and all worker threads have been destroyed, the task cache queue has been emptied or the execution finishes, the thread pool is set to the terminated state.
The thread pool function is to limit the number of threads executing in the system. According to the environment of the system, the number of threads can be set automatically or manually to achieve the best performance; less waste of system resources, more caused by the system congestion efficiency is not high. Use the thread pool to control the number of threads and other threads to wait. A task is completed, and then the first task from the queue is executed. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to run, it can start running if there are waiting worker threads in the thread pool, otherwise enter the wait queue.
Ps:
Parallelism and concurrency differences
1, parallel refers to the two at the same time to carry out a thing, such as running, two people are constantly running forward;
2, concurrency refers to the situation of limited resources, the two alternate use of resources, such as a section of the road (single-core CPU resources) at the same time only one person, a go after a period, to b,b used to continue to give a, alternating use, the purpose is to improve efficiency
Reference: Exploring the Art of Android development.
Android (thread II) thread pool details