This article is a basic article about thread pooling.
First introduce a method to get the number of CPUs:
int cpucount = Runtime.getruntime (). Availableprocessors ();
One, the disadvantage of creating asynchronous threads.
1. Each new thread creates an object, resulting in poor performance.
2, the lack of unified management, may lead to unlimited thread operation, the serious consequence is oom or crash.
Second, the advantages of enabling the thread pool.
1, reuse, reduce the creation of objects, improve performance.
2, can effectively control the number of concurrent threads, improve system resource utilization, avoid resource contention.
3, can provide a variety of functions: timing, cycle, concurrency, single and other functions.
Third, Executorservice thread pool
Java provides four types of common thread pools through executors.
1, Newcachedthreadpoll
Define a thread pool where the thread pool has reusable threads, the reuse thread executes, and if not, the new thread executes.
2, Newsinglethreadexecutor
Creates a thread pool that has only one active worker thread, an ordered (Fifo,lifo, priority order, and so on) task in the processing queue.
Executorservice singleexecutor = Executors.newsinglethreadexecutor ();
for (int i = 0; i <; i++) {
Singleexecutor.execute (New Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
}
});
}
3, Newfixedthreadpool
A thread pool that defines an available number of concurrent threads, waiting in the queue.
Executorservice Fixedthread = Executors.newfixedthreadpool (3);
for (int i = 0; i <; i + +) {
Fixedthread.execute (New Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
}
});
}
4, Newscheduledthreadpool
Create a fixed-line pool that supports timed and recurring task execution.
Scheduledexecutorservice Scheduledthread = Executors.newscheduledthreadpool (3);
Delay execution
Scheduledthread.schedule (New Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
}
}, 2*1000, timeunit.seconds);
Fixed interval execution, unaffected by any
Scheduledthread.scheduleatfixedrate (New Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
}
}, 10*1000, 1*1000, timeunit.seconds);
When the thread finishes executing, the start calculation interval is executed again
Scheduledthread.schedulewithfixeddelay (New Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
}
}, 10*1000, 1*1000, timeunit.seconds);
Iv. Ansynctask Asynchronous threads
Two thread pools are available:
1. Thread_pool_executor Asynchronous Thread pool
2. Serial_executor Sync thread pool
Attention:
1. When using Asynctask.execute () to perform asynchronous tasks by default, Serial_executor is used by default.
2, Serial_executor is on the basis of Thread_pool_executor, plus a set of tasks to maintain the order.
Android Development ThreadPool (thread pool) Summary