Comparison between four thread pool of Java and Android

Introduce drawbacks of new Thread, compare Java Android four kinds thread pool, newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool and newSingleThreadExecutor, give some sample code.

This blog mainly introduce the drawbacks of new Thread and Java four kinds of thread pool, which the same applies to Android

1. abuses of new Thread

Do you still just use new Thread to perform an asynchronous task like this?

1
2
3
4
5
6
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).start();

no cool at all!

The abuses of new Thread can outline as follows:

  • using new Thread to new an object every time is inefficient
  • lack of unified management of the thread, may be unlimited new threads, competing with each other, and may take up too much system resources lead to crash or oom.
  • lack of more features, such as timing execution, regular execution, thread interrupt.

Compared to new Thread, Java provides the benefits of the four thread pool:

  • Reusing existing threads to reduce the overhead of object creation and demise.
  • Can effectively control the number of concurrent threads, improve the utilization of system resources, while avoiding excessive competition for resources, to avoid blocking.
  • Provide regular execution, regular execution, single thread, concurrency control, and other functions.

2. Thread pool of Java

Java provides four thread pools through Executors, respectively:
(1) NewCachedThreadPool to create a cache thread pool, if the thread pool length exceeds the processing needs, can be flexible recovery of idle threads, if not recoverable, the new thread.
(2) NewFixedThreadPool to create a long-term pool, can control the maximum number of concurrent threads, the thread will wait in the queue waiting.
(3) NewScheduledThreadPool creates a fixed - line pool that supports timing and periodic task execution.
(4) NewSingleThreadExecutor creates a single threaded thread pool that performs tasks only with a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority)

2.1 newCachedThreadPool

To create a cache thread pool, if the thread pool length exceeds the processing needs, can be flexible recovery of idle threads, if not recoverable, the new thread. Sample code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(index);
}
});
}

The thread pool is infinite, and when the second task is executed, the first task is completed, and the thread of the first task is reused

2.2 newFixedThreadPool

Create a long-term pool, can control the maximum number of concurrent threads, the thread will wait in the queue waiting. Sample code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(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, each task output index after sleep 2 seconds, so print every two seconds.
It is best to set the size of the long line pool according to the system resources. Such as Runtime.getRuntime ().AvailableProcessors ()

2.3 newScheduledThreadPool

Create a long-term pool to support timing and periodic task execution. Deferred execution sample code is as follows

1
2
3
4
5
6
7
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);

which with delay of 3 seconds.

Sample code is executed periodically as follows

1
2
3
4
5
6
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);

Represents a delay of 1 second every 3 seconds.
ScheduledExecutorService is safer and more powerful than Timer

2.4 newSingleThreadExecutor

To create a single threaded thread pool, it will only use the only thread to perform the task, to ensure that all tasks in accordance with the specified order (FIFO, LIFO, priority). Sample code is as follows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

The results of the output, the equivalent of the order of each task.

Most existing GUI programs are single threaded. Android single thread can be used for database operations, file operations, the application of batch installation, the application of batch delete and so is not suitable for concurrency but may IO blocking and affect the operation of the UI thread response