Using the thread pool for Android performance optimization

Source: Internet
Author: User

When writing a program, some asynchronous programs do not need to be executed only once, in order to facilitate often write the following code

New Thread (New Runnable () {     @Override public    void Run () {        //TODO auto-generated method stub    }}). Start () ;
There are some problems with this new anonymous object.
1. Because it is anonymous, it cannot be managed
2. If you need to perform this operation more than once, you may create multiple, consuming system resources
3. Unable to perform more actions
benefits of using the thread pool
1. Can reuse existing threads and reduce overhead of the system
2. Use the thread pool to perform timing, concurrency control


Java's thread pool is also suitable for Android
The role of the thread pool:
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.
Why use a thread pool:
1. Reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks.
2. You can adjust the number of threads in the thread pool according to the endurance of the system, prevent the server from being exhausted because it consumes too much memory (approximately 1MB of memory per thread, the more threads open, the more memory is consumed and the last crashes).

Java provides four thread pools through executors, namely:
Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.
Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
Newsinglethreadexecutor 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).

1.newCachedThreadPool

/** * can cache thread pool */public static void Function1 () {Executorservice executorservice = Executors.newcachedthreadpool (); t i = 0; I < 50; i++) {Final int index = i;try {thread.sleep (100);//The Shorter the sleep time, the more threads are created} catch (Interruptedexception e) {//TODO auto-generate D catch Blocke.printstacktrace ();} Executorservice.execute (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method STUBSYSTEM.OUT.PRINTLN ("Active count =" + thread.activecount () + "index =" + index); try {thread.sleep (1000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}});}}
Print results

Active Count = 2 index = 0
Active Count = 3 index = 1
Active Count = 4 index = 2
Active count = 5 index = 3
Active Count = 6 index = 4
Active count = 7 index = 5
Active Count = 8 index = 6
Active Count = 9 index = 7
Active Count = Ten index = 8
Active count = One index = 9
Active count = one index = 10
Active count = one index = 11
Active count = one index = 12
Active count = one index = 13
Active count = one index = 14
Active count = One index = 15
Active count = One index = 16
Active count = one index = 17
Active count = One index = 18
Active count = One index = 19
Active count = one index = 20
Active count = one index = 21
Active count = one index = 22
Active count = one index = 23
Active count = One index = 24
Active count = One index = 25
Active count = one index = 26
Active count = One index = 27
Active count = one index = 28
Active count = one index = 29
Active count = One index = 30
Active count = one index = 31
Active count = one index = 32
Active count = one index = 33
Active count = one index = 34
Active count = one index = 35
Active count = one index = 36
Active count = one index = 37
Active count = one index = 38
Active count = one index = 39
Active count = one index = 40
Active count = one index = 41
Active count = one index = 42
Active count = one index = 43
Active count = one index = 44
Active count = one index = 45
Active count = one index = 46
Active count = one index = 47
Active count = one index = 48
Active Count = Ten index = 49
From the print message, the number of start threads is increasing, later stable, you can modify the sleep time, the shorter the sleep time, the more the number of threads created, because the front is not finished, the thread pool can not be executed in the need to create, if the sleep time is increased, the number of threads created will be less

2.newFixedThreadPool Create the number of threads based on the parameters passed in

/** * Fixed thread pool */public static void Function2 () {Executorservice Executorservice = Executors.newfixedthreadpool (3); for (int i = 0; I < 30; i++) {Final int index = I;executorservice.execute (new Runnable () {@Overridepublic void run () {try {System.out.println ("in Dex = "+ index+"  thread count = "+ Thread.activecount ()); Thread.Sleep (2000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}});}}
3.newScheduledThreadPool

/** * Fixed thread pool, can do delay */public static void Function3 () {Scheduledexecutorservice Executorservice = Executors.newscheduledthreadpool (5); Executorservice.schedule (new Runnable () {@Overridepublic void run () { SYSTEM.OUT.PRINTLN ("Delay 3 seconds" + "  thread count =" + Thread.activecount ());}}, 3, timeunit.seconds);} /** * Regular execution, can be used to do timer */public static void Function4 () {Scheduledexecutorservice Executorservice = Executors.newscheduledthreadpool (3); Executorservice.scheduleatfixedrate (new Runnable () {@Overridepublic void run () {SYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds" + "  thread count =" + Thread.activecount ());}}, 1, 3 , timeunit.seconds);}
Print results

Delay 1 seconds, and excute every 3 seconds  thread count = 2delay 1 seconds, and excute every 3 seconds  thread Cou NT = 3delay 1 seconds, and excute every 3 seconds  thread count = 4delay 1 seconds, and excute every 3 seconds  thre Ad count = 4delay 1 seconds, and excute every 3 seconds  thread count = 4delay 1 seconds, and excute every 3 seconds
   thread count = 4delay 1 seconds, and excute every 3 seconds  thread count = 4delay 1 seconds, and excute every 3 seco NDS  Thread count = 4delay 1 seconds, and excute every 3 seconds  thread count = 4
4.newSingleThreadExecutor This is the simplest

/** * Singleton thread */public static void Function5 () {Executorservice singlethreadexecutor = Executors.newsinglethreadexecutor (); for (int i = 0; i < 5; i++) {final int index = I;singlethreadexecutor.execute (new Runnable () {@Overridepublic void run ( {try {System.out.println ("index =" + index+ "  thread count =" + Thread.activecount ()); Thread.Sleep (1000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}});}}
Printing results:

index = 0  Thread count = 2index = 1  Thread count = 2index = 2  Thread count = 2index = 3  Thread count = 2in Dex = 4  Thread count = 2
Only one thread was created

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.