当前位置:网站首页>Why is the executor thread pool framework introduced
Why is the executor thread pool framework introduced
2022-06-24 19:31:00 【Jade label】
new Thread() The shortcomings of
Every time new Thread() Cost performance
call new Thread() The thread created lacks management , It's called a wild thread , And it can be created without limitation , Competing with each other , It will lead to excessive occupation of system resources, resulting in system paralysis .
Not conducive to expansion , For example, regular execution 、 Do it regularly 、 Thread the interrupt
The advantages of using thread pools
Reuse existing threads , Reduce object creation 、 The cost of extinction , Good performance
Can effectively control the maximum number of concurrent threads , Improve the utilization of system resources , At the same time, avoid too much resource competition , Avoid clogging
Provide timing execution 、 Do it regularly 、 Single thread 、 Concurrent data control and other functions
Executor Introduction to
stay Java 5 after , Concurrent programming introduces a bunch of new startup 、 Scheduling and managing threads API.
Executor The framework is Java 5 Introduced in ,
The thread pool mechanism is used internally , It's in java.util.cocurrent It's a bag , Through the framework to control the start of the thread 、 Execute and close , It can simplify the operation of concurrent programming . therefore , stay Java 5 after , adopt Executor To start a thread than to use Thread Of start Better way , Besides being easier to manage , More efficient ( Using thread pool to implement , Save money ) Outside , And the key point is : Help to avoid this Escape problem —— If we start a thread in the constructor , Because another task might start executing before the end of the constructor , At this point, you may access the object that is half initialized with Executor In the constructor .
Executor The framework includes : Thread pool ,Executor,Executors,ExecutorService,CompletionService,Future,Callable etc. .
Executors Methods to introduce
Executors Factory
adopt Executors Provides four thread pools ,newFixedThreadPool、newCachedThreadPool、newSingleThreadExecutor、newScheduledThreadPool.
1.public static ExecutorService newFixedThreadPool(int nThreads)
Creates a thread pool with a fixed number of threads .
2.public static ExecutorService newCachedThreadPool()
Create a cacheable thread pool , call execute The previously constructed threads are reused ( If threads are available ). If no existing thread is available , Then create a new line Cheng and add it to the pool . Terminate and remove those existing from the cache 60 Second unused thread .
3.public static ExecutorService newSingleThreadExecutor()
Create a single threaded Executor.
4.public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
Create a thread pool that supports scheduled and periodic task execution , In most cases it can be used instead Timer class .
1.newFixedThreadPool Create a thread pool that can reuse a fixed number of threads , Run these threads in a shared, unbounded queue .
Example
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 20; i++) {
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName());
}
};
executorService.execute(syncRunnable);
}Running results : Only... Will be created in total 5 Threads , Start executing five threads , When all five threads are active , Resubmitted tasks will be added to the queue until other threads finish running , When the thread is idle, it will be reused by the next task
2.newCachedThreadPool Create a cacheable thread pool , If the thread pool length exceeds processing requirements , Free threads can be recycled flexibly
Example :
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName());
}
};
executorService.execute(syncRunnable);
}Running results : It can be seen that the cache thread pool size is an indefinite value , You may need to create a different number of threads , When using cached pools , First, check whether there are any previously created threads in the pool , If there is , Just reuse . without , Add a new thread to the pool , Cache pools are often used to perform asynchronous tasks with short lifetime
3.newScheduledThreadPool Create a fixed-length thread pool , Support regular and periodic task execution
schedule(Runnable command,long delay, TimeUnit unit) Create and perform one-time operations that are enabled after a given delay
Example : Indicates that the timer starts from the submission of the task ,5000 In milliseconds, execute
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
for (int i = 0; i < 20; i++) {
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName());
}
};
executorService.schedule(syncRunnable, 5000, TimeUnit.MILLISECONDS);
}Operation results and newFixedThreadPool similar , The difference is newScheduledThreadPool It is executed after a certain time delay
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnitunit)
Create and perform a periodic operation that is enabled for the first time after a given initial delay , Subsequent operations have a given period ; That is to say, it will be in initialDelay After execution , And then in initialDelay+period After execution , And then initialDelay + 2 * period After execution , And so on
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName());
}
};
executorService.scheduleAtFixedRate(syncRunnable, 5000, 3000, TimeUnit.MILLISECONDS);scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
Create and perform a periodic operation that is enabled for the first time after a given initial delay , And then , There is a given delay between the termination of each execution and the start of the next
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executorService.scheduleWithFixedDelay(syncRunnable, 5000, 3000, TimeUnit.MILLISECONDS);4.newSingleThreadExecutor Create a single threaded thread pool , It only uses a single worker thread to perform tasks , Ensure all tasks are in the specified order (FIFO, LIFO, priority ) perform
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 20; i++) {
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName());
}
};
executorService.execute(syncRunnable);
}Running results : Only one thread will be created , The second... Will not be executed until the previous one has been executed
ExecutorService
ExecutorService It's an interface ,ExecutorService Interface inherited Executor Interface , Defines some life cycle approaches .
public interface ExecutorService extends Executor {
void shutdown();// Close in sequence ExecutorService, Stop receiving new tasks , Wait until all the submitted tasks are completed , close ExecutorService
List<Runnable> shutdownNow();// Prevent waiting for the task to start and trying to stop the currently executing task , Stop receiving new tasks , Return to the waiting task list
boolean isShutdown();// Judge whether the thread pool has been closed
boolean isTerminated();// If all tasks have been completed after closing , Then return to true. Be careful , Unless you call shutdown or shutdownNow, otherwise isTerminated Never for true.
boolean awaitTermination(long timeout, TimeUnit unit)// wait for ( Blocking ) Until shutdown or maximum waiting time or interruption occurs ,timeout - The longest waiting time ,unit - timeout Time unit of parameter If this execution procedure terminates , Then return to true; If the expiration period expires before termination , Then return to false
<T> Future<T> submit(Callable<T> task);// Submit a task with a return value to execute , Returns a... That represents the pending result of the task Future. The Future Of get Method will return the result of the task when it completes successfully .
<T> Future<T> submit(Runnable task, T result);// To submit a Runnable Tasks are used to perform , And returns a Future. The Future Of get Method will return the given result upon successful completion .
Future<?> submit(Runnable task);// To submit a Runnable Tasks are used to perform , And returns a Future. The Future Of get Methods are successful When finished, it will return to null
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)// Perform the given task , When all the tasks are completed , Returns the status and results of the task Future list . Returns the of all elements of the list Future.isDone() by true.
throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)// Perform the given task , When all the tasks are completed , Returns the status and results of the task Future list . Returns the of all elements of the list Future.isDone() by true.
throws InterruptedException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks)// Perform the given task , If a task has been successfully completed before the expiration of a given timeout period ( That is, no exception is thrown ), The result is returned . Once normal or abnormal returns , Then cancel the unfinished task .
throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}ExecutorService Interface inherited from Executor Interface , It provides a richer way to implement multithreading , such as ,ExecutorService Provides a way to close yourself , And can be generated to track the execution status of one or more asynchronous tasks Future Methods . You can call ExecutorService Of shutdown() Method to smoothly close ExecutorService, After calling this method , Will lead to ExecutorService Stop accepting any new tasks and wait for the submitted tasks to complete ( There are two categories of submitted tasks : One is already being implemented , The other is not yet implemented ), When all submitted tasks are completed, they will be closed ExecutorService. Therefore, we usually use this interface to implement and manage multithreading .
ExecutorService The life cycle of includes three states : function 、 close 、 End . After creation, it will enter the running state , When calling the shutdown() When the method is used , It enters the closed state , This means ExecutorService No more new assignments , But it is still carrying out the tasks that have been submitted , When the task that has been submitted is completed , It reaches the termination state . If you don't call shutdown() Method ,ExecutorService Will always be running , Keep receiving new tasks , Perform new tasks , The server side generally does not need to close it , Just keep running .
Executor perform Runnable Mission
once Runnable The task is passed to execute() Method , This method will automatically execute on a thread . Here is Executor perform Runnable Example code for the task :
public class TestCachedThreadPool{
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
// ExecutorService executorService = Executors.newFixedThreadPool(5);
// ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++){
executorService.execute(new TestRunnable());
System.out.println("************* a" + i + " *************");
}
executorService.shutdown();
}
}
class TestRunnable implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName() + " The thread is called .");
}
} result

Executor perform Callable Mission
stay Java 5 after , There are two types of tasks : One is the realization of Runnable The class of the interface , One is the realization of Callable The class of the interface . Both can be ExecutorService perform , however Runnable Task has no return value , and Callable The task has a return value . also Callable Of call() Method can only pass through ExecutorService Of submit(Callable task) Method to execute , And return to a Future, A task is waiting to be completed Future.
Here is a Executor perform Callable Example code for the task :
public class CallableDemo{
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<String>> resultList = new ArrayList<Future<String>>();
// establish 10 A mission and carry out
for (int i = 0; i < 10; i++){
// Use ExecutorService perform Callable Type of task , And save the results in future variable
Future<String> future = executorService.submit(new TaskWithResult(i));
// Store the task execution results to List in
resultList.add(future);
}
// The result of traversing the task
for (Future<String> fs : resultList){
try{
while(!fs.isDone);//Future Return if not done , Then we wait in a circle , until Future Back to finish
System.out.println(fs.get()); // Print each thread ( Mission ) Results of execution
}catch(InterruptedException e){
e.printStackTrace();
}catch(ExecutionException e){
e.printStackTrace();
}finally{
// Start a sequence close , Perform previously submitted tasks , But don't take on new tasks
executorService.shutdown();
}
}
}
}
class TaskWithResult implements Callable<String>{
private int id;
public TaskWithResult(int id){
this.id = id;
}
/**
* The specific process of the task , Once the mission passes to ExecutorService Of submit Method ,
* The method is automatically executed on a thread
*/
public String call() throws Exception {
System.out.println("call() Method is called automatically !!! " + Thread.currentThread().getName());
// The returned result will be Future Of get Method to get
return "call() Method is called automatically , The result of the task is :" + id + " " + Thread.currentThread().getName();
}
} Some execution results are as follows :

It can also be seen from the results ,submit First, select the idle thread to execute the task , without , Will create a new thread to execute the task . in addition , We need to pay attention to : If Future The return of has not been completed , be get() Method will block waiting , until Future Complete return , You can call isDone() Methods to judge Future Whether the return has been completed .
Custom thread pool
Custom thread pool , It can be used ThreadPoolExecutor Class creation , It has multiple constructors to create thread pools , It's easy to implement custom thread pool with this class , Here's a sample program :
public class ThreadPoolTest{
public static void main(String[] args){
// Create a waiting queue
BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20);
// Creating a thread pool , The number of threads saved in the pool is 3, The maximum number of threads allowed is 5
ThreadPoolExecutor pool = new ThreadPoolExecutor(3,5,50,TimeUnit.MILLISECONDS,bqueue);
// Create seven tasks
Runnable t1 = new MyThread();
Runnable t2 = new MyThread();
Runnable t3 = new MyThread();
Runnable t4 = new MyThread();
Runnable t5 = new MyThread();
Runnable t6 = new MyThread();
Runnable t7 = new MyThread();
// Each task is executed on a thread
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.execute(t7);
// Close thread pool
pool.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " Being implemented ...");
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
} Reference resources
http://gold.xitu.io/entry/57cbaf667db2a2007895256e
http://blog.csdn.net/ns_code/article/details/17465497
http://www.infoq.com/cn/articles/executor-framework-thread-pool-task-execution-part-01
http://www.cnblogs.com/limingluzhu/p/4858776.html
边栏推荐
- Sr-gnn shift robot gnns: overlapping the limitations of localized graph training data
- Fabric ledger data block structure analysis (I): how to analyze the smart contract transaction data in the ledger
- 一次 MySQL 误操作导致的事故,高可用都不顶不住!
- 物联网?快来看 Arduino 上云啦
- 一文理解OpenStack网络
- At present, only CDC monitors Mysql to get the data of new columns. Sqlserver can't, can it
- 制造业项目MDM主数据项目实施心得
- 8 challenges of BSS application cloud native deployment
- SaltStack State状态文件配置实例
- Buddha bless you that there will never be a bug
猜你喜欢

PHP OSS file reads and writes files, and workman generates temporary files and outputs them to the browser for download

Understanding openstack network

技术实现 | Apache Doris 冷热数据存储(一)

Northwestern Polytechnic University attacked by hackers? Two factor authentication changes the situation!

Network security review office starts network security review on HowNet

The efficiency of okcc call center data operation

Generate the last login user account report of the computer through SCCM SQL

Unity mobile game performance optimization spectrum CPU time-consuming optimization divided by engine modules

Interpreting harmonyos application and service ecology

Freeswitch uses origin to dialplan
随机推荐
智能合约安全审计入门篇 —— delegatecall (2)
Php OSS file read and write file, workerman Generate Temporary file and Output Browser Download
请教一个问题。adbhi支持保留一个ID最新100条数据库,类似这样的操作吗
Real time rendering: the difference between real-time, offline, cloud rendering and hybrid rendering
企业网络管理员必备的故障处理系统
flink cdc全量读mysql老是报这个错怎么处理
数字孪生行业案例:智慧港口数字化
想问下 pgsql cdc 账号同一个 多个 task 会有影响吗,我现在3个task 只有一个 有
finkcdc支持sqlserver2008么?
cdc sql表里面的datetime要用什么类型替换
《Go题库·11》channel的应用场景
[leetcode] rotation series (array, matrix, linked list, function, string)
Experience of MDM master data project implementation for manufacturing projects
Source code analysis of ArrayList
Xiaobai, let me ask you guys, is MySQL binlog extracted by CDC in strict order
NFT质押流动性挖矿系统开发技术
8 challenges of BSS application cloud native deployment
模块五
Ask a question. Adbhi supports the retention of 100 databases with the latest IDs. Is this an operation like this
Landcover100, planned land cover website