Java thread pool ExecutorService
1. Thread pool
1.1 Under what circumstances do you use thread pool?
1.2 Benefits of using thread pools
2.ExecutorService and Executors
2.1 Introduction
ExecutorService is an interface that inherits Executor,
public interface ExecutorService extend Executor{}Executor is also an interface, which only contains one method:
public interface Executor { void execute(Runnable command);} The top-level interface of thread pool in Java is Excutor, but strictly speaking >>Exector is not a thread pool, but just a tool for executing threads. The real thread>pool interface is ExecutorService.
3.Executors
It is a static factory class, which can produce different types of thread pools, and some of the source codes are as follows:
public class Executors {//newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}//newCacheThreadPool public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>()); } //newScheduledThreadPool public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } //newStringooo}Let’s first look at a specific example and use examples to illustrate the similarities and differences between them.
package thread;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;/** * Created by yang on 16-7-11. */public class Ch09_Executor { private static void run(ExecutorService threadPool) { for (int i = 1; i < 5; i++) { final int taskID=i; threadPool.execute(new Runnable() { @Override public void run() { for(int i=1;i<5;i++){ try{ Thread.sleep(20); }catch (InterruptedException e) { e.printStackTrace(); } System.out.println("+taskID+"execution" of the task); } } } }); } threadPool.shutdown(); } public static void main(String[] args) { //Create a thread pool that can accommodate 3 threads ExecutorService fixedThreadPool= Executors.newFixedThreadPool(3); //The size of the thread pool will be dynamically allocated according to the executed task ExecutorService cacheThreadPool=Executors.newCachedThreadPool(); //Create a thread pool of a single thread. If the current thread suddenly interrupts while executing the task, a new thread will be created to replace it and continue execution. ExecutorService singleThreadPool=Executors.newSingleThreadExecutor(); // The effect is similar to the Timer timer ScheduledExecutorService scheduledThreadPool=Executors.newScheduledThreadPool(3); // run(fixedThreadPool); //(1) //run(cacheThreadPool); //(2) // run(singleThreadPool); //(3) // run(scheduledThreadPool); //(4) }}4. 4 commonly used thread pools
4.1 CachedThreadPool
CachedThreadPool will create a cache area that caches the initialized thread, terminates and removes threads that have not been used for 6 seconds from the cache.
If the thread is available, use the thread that was created before. If the thread is not available, create a new thread.
.Reuse:
Cache-type pool, first check if there are threads that have been created in the pool. If there is one, reuse. If there is no one, create a new thread and add it to the pool.
Use scenarios:
Cache pools are usually used to perform some asynchronous tasks with short lifetimes, so they are not used much in some connection-oriented Daemon-type SERVERs.
time out:
The thread that can be reuse must be a thread in the pool within the timeout IDLE. The default timeout is 60s. If the duration of this IDLE is exceeded, the thread instance will be terminated and the pool will be removed.
Finish:
The thread put into the CachedThreadPool does not have to worry about its end. If it is inactive after TIMEOUT, it will be automatically terminated.
Example explanation:
Remove the comments of (2) and run them. The result of the operation is as follows:
The first time of the first task, the third time of the third task, the third time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the third time of the third time of the second time of the second time of the second time of the third time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time
From the results, it can be seen that the 4 tasks are executed alternately.
4.2FixedThreadPool
In FixedThreadPool, there is a fixed-size pool,
If the tasks currently need to be executed exceed the pool size, then many outgoing tasks are in a waiting state until there are free threads to execute the tasks.
If the task currently required to be executed is smaller than the pool size, the idle thread will not be destroyed.
Reuse:
fixedThreadPool is similar to cacheThreadPool, and it can also be used if it can be reuse, but you cannot create new threads at any time.
Fixed number
Its uniqueness is that at any time point, there can only be a fixed number of active threads. At this time, if there is a new thread to be established, it can only be placed in another queue and wait until a thread in the current thread terminates and is moved out of the pool directly.
time out:
Unlike cacheThreadPool, FixedThreadPool does not have an IDLE mechanism
Use scenarios:
Therefore, most FixedThreadPool is aimed at some very stable and fixed regular concurrent threads, and is mostly used in servers
Source code analysis:
Judging from the source code of the method, the cache pool and the fixed pool call the same underlying pool, but the parameters are different.
The fixed pool thread count is fixed and is 0 seconds IDLE (no IDLE)
The number of cache pool threads supports 0-Integer.MAX_VALUE (obviously, the host's resource tolerance is not considered at all), 60 seconds IDLE
Example explanation:
Remove the comments of (1), and the running result is as follows:
The first time of the first task, the third time of the third time of the first task, the third time of the second time of the second task, the third time of the second time of the second time of the second task, the third time of the third time of the second time of the second task, the third time of the third time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time
A fixed-size thread pool was created with a capacity of 3, and then 4 tasks were executed in a loop. From the output results, it can be seen that the first 3 tasks were executed first, and then the idle threads performed the fourth task.
4.3SingleThreadExecutor
Remove (3) comments. See the execution result as follows:
The first task of the first task of the first task of the second task of the first task of the third task of the first task of the fourth task of the second task of the second task of the second task of the second task of the second task of the second task of the second task of the third task of the third task of the third task of the third task of the third task of the third task of the third task of the third task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task
The four tasks are executed sequentially.
4.4 ScheduledThreadPool
ScheduledThreadPool is a fixed-size thread pool. Similar to FixedThreadPool, the tasks executed are timed tasks.
The result obtained by removing the annotation of (4) is the same as the result obtained by FixedThreadPool. The main reason for ScheduledThreadPool is not here, but a timed task. See the following example:
package thread;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;/** * Created by yang on 16-7-11. */public class MyScheduledTask implements Runnable { private String tname; public MyScheduledTask(String name){ this.tname=name; } public void run(){ System.out.println(tname+"Task delay execution 2 seconds!"); } public static void main(String[] args) { ScheduledExecutorService scheduledPool=Executors.newScheduledThreadPool(2); ScheduledExecutorService singSchedulePool=Executors.newSingleThreadScheduledExecutor(); MyScheduledTask mt1=new MyScheduledTask("mt1"); MyScheduledTask mt2=new MyScheduledTask("mt2"); //Start the mt1 task with scheduledThreadPool to execute scheduledPool.schedule(mt1,2, TimeUnit.SECONDS); //Start mt2 with singlescheduledthreadPool; singSchedulePool.schedule(mt2,2000, TimeUnit.MILLISECONDS); scheduledPool.shutdown(); singSchedulePool.shutdown(); }}result:
mt1 task delays 2 seconds to execute! mt2 task delays 2 seconds to execute!
The result will not be displayed after the program is run for 2 seconds, indicating that the thread was executed after 2 seconds.
Thank you for reading, I hope it can help you. Thank you for your support for this site!