Introducing the drawbacks of new thread and the use of Java four thread pools are also applicable to Android. This article is a basic article and will share some of the advanced features of the thread pool later.
1. The disadvantage of new thread
Perform an asynchronous task are you still just following the new thread?
New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated Method stub}}). Start ();
Then you are out too much, and the drawbacks of new thread are as follows:
A. Each new thread creates a poor performance for the newly created object.
B. Lack of unified management of threads, the possibility of unlimited new threads, competing with each other, and potentially consuming excessive system resources can lead to freezing or oom.
C. Lack of additional functionality, such as timed execution, periodic execution, and thread interruption.
The benefits of the four thread pools provided by new Thread,java are:
A. Reusing existing threads, reducing the cost of object creation, extinction, and performance.
B. Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, avoid clogging.
C. Provide functions such as timed execution, periodic execution, single-threaded, concurrency control, etc.
2. Java thread Pool
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
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. The sample code is as follows:
Executorservice Cachedthreadpool = Executors.newcachedthreadpool (); for (int i = 0; i <; i++) {final int index = I;TR Y {thread.sleep (Index *),} catch (Interruptedexception e) {e.printstacktrace ();} cachedthreadpool.execute (New Runnable () {@Overridepublic void run () {System.out.println (index);}});
The thread pool is infinitely large, and when the first task is completed when the second task is performed, the threads that perform the first task are reused instead of each new thread.
(2). Newfixedthreadpool
Creates a thread pool that controls the maximum number of concurrent threads, and the excess threads 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;fix Edthreadpool.execute (New Runnable () {@Overridepublic void run () {try {System.out.println (index); Thread.Sleep (2000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}});}
Because the thread pool size is 3, each task outputs index after sleep for 2 seconds, so 3 digits are printed every two seconds.
The size of a fixed-length pool is best set based on 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 () {@Overridepublic void run () {System.out.println ("Delay 3 Seconds"),}}, 3, timeunit.seconds);
Represents a delay of 3 seconds for execution.
The sample code is executed periodically as follows:
Scheduledthreadpool.scheduleatfixedrate (New Runnable () {@Overridepublic void run () {System.out.println ("Delay 1 Seconds, and excute every 3 seconds ");}, 1, 3, timeunit.seconds);
Represents a delay of 1 seconds after every 3 seconds.
Scheduledexecutorservice is safer and more powerful than a timer, and there is a separate comparison in the back.
(4), 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). The sample code is as follows:
Executorservice singlethreadexecutor = Executors.newsinglethreadexecutor (); for (int i = 0; i <; i++) {final int Inde x = I;singlethreadexecutor.execute (new Runnable () {@Overridepublic void run () {try {System.out.println (index); Thread.Sleep (2000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}});}
The results are output sequentially, which is equivalent to performing each task sequentially.
Most of the current GUI programs are single-threaded. Single-threaded Android can be used for database operations, file operations, application batch installation, application bulk deletion, etc. that are not suitable for concurrency but may have IO blocking and affect UI thread response actions.
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).
The top interface of the thread pool in Java is executor, but strictly speaking, 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 |
A true thread pool interface. |
Scheduledexecutorservice |
can be similar to Timer/timertask to solve problems that require repetitive execution of tasks. |
Threadpoolexecutor |
The default implementation of Executorservice. |
Scheduledthreadpoolexecutor |
Inheriting Threadpoolexecutor's Scheduledexecutorservice interface implementation, the class implementation of periodic task scheduling. |
To configure a thread pool is more complex, especially if the thread pool principle is not very clear, it is likely that the thread pool configured is not superior, so there are some static factories in the executors class that generate some common thread pools.
1. Newsinglethreadexecutor
Creates a single threaded pool of threads. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.
2.Newfixedthreadpool
Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.
3. Newcachedthreadpool
Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread that is required to process the task,
Then a partially idle (60 second non-performing) thread 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 size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create.
4.Newscheduledthreadpool
Create a thread pool of unlimited size. This thread pool supports the need to schedule and periodically perform tasks.
Instance
1:newsinglethreadexecutor
Mythread.java
public class MyThread extends Thread { @Override public void Run () { System.out.println ( Thread.CurrentThread (). GetName () + "executing ... "); }}
Testsinglethreadexecutor.java
public class Testsinglethreadexecutor {public static void Main (string[] args) { //Create a thread pool that can reuse a fixed number of threads Executorservice pool = executors. Newsinglethreadexecutor (); The Runnable interface object is created, and the thread object of course implements the Runnable interface thread t1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread (); Put the thread into the pool for execution pool.execute (t1); Pool.execute (T2); Pool.execute (T3); Pool.execute (T4); Pool.execute (T5); Close the thread pool pool.shutdown (); }}
Output results
Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ...
2:newfixedthreadpool
Testfixedthreadpool.java
Publicclass Testfixedthreadpool { publicstaticvoid main (string[] args) { //Create a thread pool that can be reused for a fixed number of threads Executorservice pool = Executors.newfixedthreadpool (2); The Runnable interface object is created, and the thread object of course implements the Runnable interface thread t1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread (); Put the thread into the pool for execution pool.execute (t1); Pool.execute (T2); Pool.execute (T3); Pool.execute (T4); Pool.execute (T5); Close the thread pool pool.shutdown (); }}
Output results
Pool-1-thread-1 is executing ... Pool-1-thread-2 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-2 is executing ... Pool-1-thread-1 is executing ...
3:Newcachedthreadpool
Testcachedthreadpool.java
public class Testcachedthreadpool {public static void Main (string[] args) { //Create a thread pool that can reuse a fixed number of threads Executorservice pool = Executors.newcachedthreadpool (); The Runnable interface object is created, and the thread object of course implements the Runnable interface thread t1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread (); Put the thread into the pool for execution pool.execute (t1); Pool.execute (T2); Pool.execute (T3); Pool.execute (T4); Pool.execute (T5); Close the thread pool pool.shutdown (); }}
Output Result:
Pool-1-thread-2 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-3 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-5 is executing ...
4:Newscheduledthreadpool
Testscheduledthreadpoolexecutor.java
public class Testscheduledthreadpoolexecutor {public static void Main (string[] args) { Scheduledthreadpoolexecutor exec = new Scheduledthreadpoolexecutor (1); Exec.scheduleatfixedrate (New Runnable () {//Every time the exception is triggered @Override publicvoid Run () { //throw new RuntimeException (); System.out.println ("================");}, + , timeunit.milliseconds); Exec.scheduleatfixedrate (New Runnable () {//Print the system time every once in a while to prove that the two do not affect each other @Override publicvoid Run () { System.out.println (System.nanotime ());}}, +, + , timeunit.milliseconds);} }
Output results
================838464454951683866438290348388643830710================839064385138383926438793198400643939383
Transfer from http://www.cnblogs.com/zhujiabin/p/5404771.html
Java Four thread pool Newcachedthreadpool,newfixedthreadpool,newscheduledthreadpool,newsinglethreadexecutor