Reprint http://www.cnblogs.com/zhujiabin/p/5404771.html
Describes the drawbacks of new thread and the use of Java four thread pools, which is also true for Android. This article is a basic article that will share some advanced features of the thread pool later.
1, the drawbacks of new thread
Perform an asynchronous task you are just the following new thread.
New Thread (New Runnable () {
@Override public
void Run () {
//TODO auto-generated method stub
}
}). Start ();
Then you are out too much, the disadvantages of new thread are as follows:
A. New thread creates poor performance each time.
B. Threads lack unified management, may create unlimited new threads, compete with each other, and may consume excessive system resources causing panic or oom.
C. Lack of additional functionality, such as timed execution, regular execution, and thread disruption.
The benefits of the four thread pools offered by the new Thread,java are:
A. Reusing existing threads, reducing the overhead of object creation, extinction, and good performance.
B. Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, avoid congestion.
C. Provide functions such as timed execution, regular execution, single thread, concurrent number control.
2. Java thread Pool
Java provides four thread pools through executors, respectively:
Newcachedthreadpool creates a cacheable thread pool that, if the thread pool length exceeds the processing needs, is flexible enough to reclaim idle threads and, if not recyclable, create a new thread.
Newfixedthreadpool creates a fixed-line pool that controls the maximum number of concurrent threads, and the threads that are exceeded 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 performed in the specified order (FIFO, LIFO, priority).
(1). Newcachedthreadpool
Creates a cacheable thread pool that, if the thread pool length exceeds processing needs, is flexible enough to reclaim idle threads and, if not recyclable, create a new thread. The sample code is as follows:
Executorservice Cachedthreadpool = Executors.newcachedthreadpool ();
for (int i = 0; i < 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 the first task is completed when the second task is performed, and the thread that executes the first task is reused instead of creating a new thread at a time.
(2). Newfixedthreadpool
Creates a fixed-line pool that controls the maximum number of concurrent threads, and the threads that are exceeded wait in the queue. The sample code is as follows:
Executorservice Fixedthreadpool = Executors.newfixedthreadpool (3);
for (int i = 0; i < i++) {
final int index = i;
Fixedthreadpool.execute (New Runnable () {
@Override public
void Run () {
try {
System.out.println () index);
Thread.Sleep ();
} catch (Interruptedexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
}}}
);
}
Because the thread pool size is 3, each task outputs index sleep 2 seconds, so print 3 digits every two seconds.
The size of the fixed-length pool is best set according to system resources. such as Runtime.getruntime (). Availableprocessors (). Refer to Preloaddatacache.
(3) Newscheduledthreadpool
Create a fixed-line pool that supports timed and recurring task execution. The deferred execution sample code is as follows:
Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5);
Scheduledthreadpool.schedule (New Runnable () {
@Override public
void Run () {
System.out.println () Delay 3 seconds ");
}
, 3, timeunit.seconds);
Indicates a delay of 3 seconds for execution.
Execute the sample code regularly as follows:
Scheduledthreadpool.scheduleatfixedrate (New Runnable () {
@Override public
void Run () {
SYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds");
}
, 1, 3, timeunit.seconds);
Indicates that the delay is performed every 3 seconds after 1 seconds.
Scheduledexecutorservice is safer and more powerful than a timer, and a separate comparison will be made later.
(4), Newsinglethreadexecutor
Creates a single-threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are performed in the specified order (FIFO, LIFO, priority). The sample code is as follows:
Executorservice singlethreadexecutor = Executors.newsinglethreadexecutor ();
for (int i = 0; i < i++) {
final int index = i;
Singlethreadexecutor.execute (New Runnable () {
@Override public
void Run () {
try {
SYSTEM.OUT.PRINTLN (index);
Thread.Sleep ();
} catch (Interruptedexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
}}}
);
}
The results are output sequentially, which is equivalent to performing each task sequentially.
Most of the current GUI programs are single-threaded. Android single-threaded can be used for database operations, file operations, application of bulk installations, application of bulk deletions, etc. that are not suitable for concurrent but possibly IO blocking and affect UI thread responses.
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, can automatically or manually set the number of threads to achieve the best effect of the operation, less waste of system resources, many caused the system congestion efficiency is not high. The thread pool controls the number of threads, and other threads wait in line. A task completes, and the first task from the queue is executed. If there is no waiting process in the queue, this resource in the thread pool is waiting. When a new task needs to be run, it can start running if there is a waiting worker thread in the thread pool, otherwise enter the wait queue.
Why do I use a thread pool:
1. The number of times to create and destroy threads is reduced, and each worker thread can be reused to perform multiple tasks.
2. According to the system's affordability, adjust the number of threads in the thread pool, to prevent the use of excessive memory, and the server tired down (each thread needs about 1MB of memory, the more threads open, the consumption of memory will be larger, the last crash).
The top-level interface in the Java thread pool is executor, but in the strictest sense executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice.
Some of the more important classes:
|
Executorservice |
The true thread pool interface. |
|
Scheduledexecutorservice |
can be similar to Timer/timertask to solve problems that require repetitive tasks. |
|
Threadpoolexecutor |
The default implementation of the Executorservice. |
|
Scheduledthreadpoolexecutor |
Inherit Threadpoolexecutor Scheduledexecutorservice interface implementation, periodic task scheduling class implementation. |
It is more complicated to configure a thread pool, especially if the thread pool is not clearly understood, it is likely that the configured thread pool is not superior, so there are some static factories in the executors class that generate some common thread pools.
1. Newsinglethreadexecutor
Create a single-threaded thread pool. This thread pool has only one threads working, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, then there is a new thread to replace it. This thread pool guarantees that the order in which all tasks are performed is performed in the order in which they are submitted.
2.newFixedThreadPool
Create a fixed size thread pool. Create a thread each time a task is committed, until the thread reaches the maximum size of the thread pool. The size of the thread pool will remain unchanged once it reaches its maximum value, and if a thread ends up executing an exception, the thread pool complements a new thread.
3. Newcachedthreadpool
Create a cacheable pool of threads. If the thread pool is larger than the threads needed to process the task,
A thread that is partially idle (60 seconds without a task) 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 thread pool size, and the thread pool size is entirely dependent on the maximum threading size that the operating system (or JVM) can create.
4.newScheduledThreadPool
Create a thread pool of infinite size. This thread pool supports the need for timing and periodic execution of tasks.
Instance
1:newsinglethreadexecutor
Mythread.java
public class Mythread extends Thread {
@Override public
void Run () {
System.out.println ( Thread.CurrentThread (). GetName () + "is executing ... ");
}
}