Android (java) thread pool: ExecutorService and Executors

Source: Internet
Author: User

ExecutorService is a service in the thread pool. It can be closed at any time and inherits Executor. Executors is a factory class dedicated to creating various thread pools

Introduces the disadvantages of new Thread and the use of four Java Thread pools, which is also applicable to Android. This article is a basic article. Later I will share some advanced features of the thread pool.

1. disadvantages of new Thread
Do you still have the following new Thread to execute an asynchronous task?

Java
 
1234567 New Thread (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub}). start ();

You have too many threads. the disadvantages of new Thread are as follows:

A. The performance of each new object created by the new Thread is poor.
B. There is a lack of unified management of threads, and there may be no restrictions on the creation of new threads, competition between them, and the possibility of occupying too much system resources, resulting in crashes or oom.
C. Lack of more functions, such as scheduled execution, regular execution, and thread interruption.
Compared with new Thread, Java provides the following four Thread pools:
A. reuse existing threads to reduce the overhead of object creation and elimination, and improve performance.
B. It can effectively control the maximum number of concurrent threads, improve the usage of system resources, and avoid excessive resource competition and congestion.
C. provides scheduled execution, regular execution, single thread, concurrency control, and other functions.

2. Java Thread Pool
Java provides four thread pools through Executors:
NewCachedThreadPool creates a cache thread pool. If the thread pool length exceeds the processing requirement, Idle threads can be recycled flexibly. If no thread pool length exists, a new thread is created.
NewFixedThreadPool creates a fixed-length thread pool, which can control the maximum number of concurrent threads. threads that exceed the limit will wait in the queue.
NewScheduledThreadPool creates a fixed-length thread pool that supports scheduled and periodic task execution.
NewSingleThreadExecutor creates a single-threaded thread pool. It only uses a unique worker thread to execute tasks, ensuring that all tasks are executed in the specified Order (FIFO, LIFO, priority.

(1). newCachedThreadPool
Create a cache thread pool. If the thread pool length exceeds the processing requirement, free threads can be recycled flexibly. If no thread pool can be recycled, a new thread is created. The sample code is as follows:

Java
 
1234567891011121314151617 ExecutorServicecachedThreadPool = Executors. newCachedThreadPool (); for (inti = 0; I <10; I ++) {finalintindex = I; try {Thread. sleep (index * 1000);} catch (InterruptedExceptione) {e. printStackTrace ();} cachedThreadPool.exe cute (newRunnable () {@ Override publicvoidrun () {System. out. println (index );}});}

The thread pool is infinite. When the second task is executed and the first task is completed, the thread for executing the first task is reused instead of creating a new thread each time.

(2). newFixedThreadPool
Create a fixed-length thread pool to control the maximum number of concurrent threads. threads that exceed the limit will wait in the queue. The sample code is as follows:

Java
 
1234567891011121314151617 ExecutorService fixedThreadPool = Executors. newFixedThreadPool (3); for (int I = 0; I <10; I ++) {final int index = I; fixedThreadPool.exe cute (new Runnable () {@ Override public void run () {try {System. out. println (index); Thread. sleep (2000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();}}});}

Because the thread pool size is 3 and each task outputs an index and sleep for 2 seconds, three numbers are printed every two seconds.

It is best to set the size of the fixed-length thread pool based on system resources. For example, Runtime. getRuntime (). availableProcessors (). See PreloadDataCache.

(3) newScheduledThreadPool
Creates a fixed-length thread pool that supports scheduled and periodic task execution. Example code of delayed execution:

Java
 
12345678 ScheduledExecutorServicescheduledThreadPool = Executors. newScheduledThreadPool (5); scheduledThreadPool. schedule (newRunnable () {@ Override publicvoidrun () {System. out. println ("delay 3 seconds") ;}, 3, TimeUnit. SECONDS );

The execution is delayed by 3 seconds.

Periodically execute the following sample code:

Java
 
1234567 ScheduledThreadPool. scheduleAtFixedRate (new Runnable () {@ Override public void run () {System. out. println ("delay 1 seconds, and excute every 3 seconds") ;}}, 1, 3, TimeUnit. SECONDS );

It indicates that the task is executed every 3 seconds after a delay of 1 second.

ScheduledExecutorService is safer and more powerful than Timer, and will be compared separately later.

(4) newSingleThreadExecutor
Create a single-threaded thread pool. It only uses a unique worker thread to execute tasks and ensures that all tasks are executed in the specified order (FIFO, LIFO, priority. The sample code is as follows:

Java
 
1234567891011121314151617 ExecutorServicesingleThreadExecutor = Executors. newSingleThreadExecutor (); for (inti = 0; I <10; I ++) {finalintindex = I; singleThreadExecutor.exe cute (newRunnable () {@ Override publicvoidrun () {try {System. out. println (index); Thread. sleep (2000);} catch (InterruptedExceptione) {// TODO Auto-generated catch block e. printStackTrace ();}}});}

The results are output in sequence, which is equivalent to executing each task in sequence.

Currently, most GUI programs are single-threaded. A single thread in Android can be used for operations such as database operations, file operations, batch installation of applications, batch deletion of applications, and other operations that are not suitable for merging and sending but may be IO obstructive and affect the UI thread response.


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.