In Java development, sometimes encountered multi-threading development, directly using the thread operation, the performance and maintenance of the program is a problem, using the Java provided by the thread pool to operate can be a good solution to the problem.
The disadvantage of new thread
Perform an asynchronous task are you still just following the new thread?
New Thread (New Runnable () { @Override public void Run () { //todo auto-generatedmethod stub } }). Start ();
Then you are out too much, and the drawbacks of new thread are as follows:
1. Each new thread has poor performance.
2, the thread lacks the unified management, may the unrestricted new thread, competes with each other, may occupy excessive system resources to cause the freezing or oom.
3, lack of more functions, such as scheduled tasks, regular execution, thread interruption.
The benefits of the four thread pools provided by new Thread,java are:
1, the reuse of existing threads, reduce the creation of objects, the cost of extinction, better performance.
2, can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, to avoid clogging.
3. Provide the functions of timing execution, regular execution, single thread, concurrency control, etc.
Second, 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:
Packagetest; ImportJava.util.concurrent.ExecutorService; Importjava.util.concurrent.Executors; Public classThreadpoolexecutortest { Public Static voidMain (string[] args) {Executorservice Cachedthreadpool=Executors.newcachedthreadpool (); for(inti = 0; I < 10; i++) {Final intindex =i; Try{thread.sleep (index* 1000); } Catch(interruptedexception e) {e.printstacktrace (); } cachedthreadpool.execute (NewRunnable () { Public voidrun () {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:
Packagetest; ImportJava.util.concurrent.ExecutorService; Importjava.util.concurrent.Executors; Public classThreadpoolexecutortest { Public Static voidMain (string[] args) {Executorservice Fixedthreadpool= Executors.newfixedthreadpool (3); for(inti = 0; I < 10; i++) { Final intindex =i; Fixedthreadpool.execute (NewRunnable () { Public voidrun () {Try{System.out.println (index); Thread.Sleep (2000); } Catch(interruptedexception e) {e.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 ().
3, Newscheduledthreadpool:
Create a fixed-line pool that supports timed and recurring task execution. The deferred execution sample code is as follows:
Packagetest; Importjava.util.concurrent.Executors; ImportJava.util.concurrent.ScheduledExecutorService; ImportJava.util.concurrent.TimeUnit; Public classThreadpoolexecutortest { Public Static voidMain (string[] args) {Scheduledexecutorservice Scheduledthreadpool= Executors.newscheduledthreadpool (5); Scheduledthreadpool.schedule (NewRunnable () { Public voidrun () {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:
Packagetest; Importjava.util.concurrent.Executors; ImportJava.util.concurrent.ScheduledExecutorService; ImportJava.util.concurrent.TimeUnit; Public classThreadpoolexecutortest { Public Static voidMain (string[] args) {Scheduledexecutorservice Scheduledthreadpool= Executors.newscheduledthreadpool (5); Scheduledthreadpool.scheduleatfixedrate (NewRunnable () { Public voidrun () {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.
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:
Packagetest; ImportJava.util.concurrent.ExecutorService; Importjava.util.concurrent.Executors; Public classThreadpoolexecutortest { Public Static voidMain (string[] args) {Executorservice singlethreadexecutor=Executors.newsinglethreadexecutor (); for(inti = 0; I < 10; i++) { Final intindex =i; Singlethreadexecutor.execute (NewRunnable () { Public voidrun () {Try{System.out.println (index); Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } } }); } } }
The results are output sequentially, which is equivalent to performing each task sequentially.
You can monitor the number of threads we create, run a non-terminating thread, and create a specified amount of threads, using the JDK's own monitoring tools to observe:
Tools Catalog: C:\Program files\java\jdk1.6.0_06\bin\jconsole.exe
Run the program to make a slight change:
Packagetest; ImportJava.util.concurrent.ExecutorService; Importjava.util.concurrent.Executors; Public classThreadpoolexecutortest { Public Static voidMain (string[] args) {Executorservice singlethreadexecutor=Executors.newcachedthreadpool (); for(inti = 0; I < 100; i++) { Final intindex =i; Singlethreadexecutor.execute (NewRunnable () { Public voidrun () {Try { while(true) {System.out.println (index); Thread.Sleep (10 * 1000); } } Catch(interruptedexception e) {e.printstacktrace (); } } }); Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } } } }
The effect is as follows:
Select the program we run:
Monitor running status
Third, 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.
Iv. Why to use the thread pool:
1, reduce the number of times to create and destroy threads, each worker thread can be reused to perform multiple tasks.
2, according to the system's ability to withstand, adjust the number of threads in the thread pool, to prevent the consumption of excessive memory, and the server tired down (each thread needs about 1MB of memory, the more threads open, the more memory consumed, the last crash).
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: The real thread pool interface.
Scheduledexecutorservice: Can be similar to Timer/timertask to solve the problem that requires the task to be executed repeatedly.
The default implementation of Threadpoolexecutor: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 required to process the task, then a partially idle (60 second non-performing task) 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
Creates a thread pool with a fixed size. This thread pool supports the need to schedule and periodically perform tasks.
Sample code
A fixed-size thread pool, Newfixedthreadpool:
Package app.executors; Import java.util.concurrent.Executors; Import Java.util.concurrent.ExecutorService; /** * java thread: Thread pool * * @author Xiho * * public class Test {public static void main (string[] args) {//Create a reusable fixed thread pool of threads executorservice pool = executors.newfixedthreadpool (2);//threads 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 thread pool Pool.shutdown ();} } class MyThread extends Thread {@Override public void run () {System.out.println (Thread.CurrentThread (). GetName () + " Yes... "); } }
Output Result:
Pool-1-thread-1 is executing ... Pool-1-thread-3 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-2 is executing ... Pool-1-thread-5 is executing ...
Change the parameters in Executorservice pool = Executors.newfixedthreadpool (5): Executorservice pool = Executors.newfixedthreadpool (2), The output is:
Pool-1-thread-1 is executing ... pool-1-thread-1 is executing ... pool-1-thread-2 is executing ... pool-1-thread-1 is executing ... pool-1-thread-2 is executing ...
As can be seen from the above results, the Newfixedthreadpool parameter specifies the maximum number of threads that can be run, which will not run after the number of lines loads in. Second, threads that join the thread pool are managed, and the threads are not affected by the order of accession.
Second, single task thread pool, Newsinglethreadexecutor:
Just change the Executorservice pool = Executors.newfixedthreadpool (2) in the above code to Executorservice pool = Executors.newsinglethreadexecutor ();
Output Result:
Pool-1-thread-1 is executing ... pool-1-thread-1 is executing ... pool-1-thread-1 is executing ... pool-1-thread-1 is executing ...
As you can see, each call to the Execute method is, in fact, the last call to the Thread-1 run method.
Three, variable size thread pool, Newcachedthreadpool:
Similar to the above, just change the way the pool was created: executorservice pool = Executors.newcachedthreadpool ();
Output Result:
Pool-1-thread-1 is executing ... pool-1-thread-2 is executing ... pool-1-thread-4 is executing ... pool-1-thread-3 is executing ... pool-1-thread-5 is executing ...
This approach is characterized by the creation of thread pools for new threads as needed, but reusing them when previously constructed threads are available.
Iv. delayed Connection pool, Newscheduledthreadpool:
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 Result:
================ 8384644549516 8386643829034 8388643830710 ================ 8390643851383 8392643879319 8400643939383
Learning and summarizing of Java four thread pool