当前位置:网站首页>Seven ways to create thread pools
Seven ways to create thread pools
2022-07-22 09:14:00 【Ugly and ugly】
stay Java In language , Concurrent programming is often achieved through the bedstead thread pool , There are many ways to create thread pools , Each thread pool creation method corresponds to different usage scenarios . In summary, the creation of thread pools can be divided into two categories :
adopt Executors establish
adopt ThreadPoolExecutor establish
The above two ways to create thread pools are 7 A specific implementation method , this 7 These methods are the seven ways to create thread pools that this article will talk about . Namely :
Method | meaning |
---|---|
Executors.newFixedThreadPool() | Create a fixed size thread pool , Control the number of concurrent threads , The exceeded thread will wait in the queue |
Executors.newCachedThreadPool() | Create a cacheable thread pool , If the number of threads exceeds the number required for processing , The cache will be recycled after a period of time , If there are not enough threads , New thread |
Executors.newSingleThreadExecutor() | Create a thread pool for a single thread , It can ensure the execution sequence of first in first out |
Executors.newScheduledThreadPool() | Create a pool of threads that can perform deferred tasks |
Executors.newSingleThreadScheduledExecutor() | Create a single threaded pool of threads that can perform deferred tasks |
Executors.newWorkStealingPool() | Create a preemptive thread pool |
ThreadPoolExecutor() | Create thread pool manually , Relevant parameters can be customized |
Executors.newFixedThreadPool(): Create a fixed-size thread pool , Control the number of concurrent threads .
public class FixedThreadPoolDemo {
public static void main(String[] args) {
// establish 2 A pool of threads
ExecutorService threadPool = Executors.newFixedThreadPool(2);
// Create tasks
Runnable runnable = () -> System.out.println(" Task performed , Threads :" + Thread.currentThread().getName());
// Thread pool execution task ( Add... At a time 8 A mission )
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
threadPool.execute(runnable);
}
}
Create a 2 A pool of threads , perform 8 A mission , The execution result is :
Executors.newCachedThreadPool(): Create a cacheable thread pool , If the number of threads exceeds what the character needs , Then the redundant threads will be cached for a period of time and then recycled , If there are not enough threads , A new thread will be created .
public class CachedThreadPoolDemo {
public static void main(String[] args) {
// Creating a thread pool
ExecutorService threadPool = Executors.newCachedThreadPool();
// Perform tasks
for (int i = 0; i < 5; i++) {
threadPool.execute(() -> {
System.out.println(" Task performed , Threads :" + Thread.currentThread().getName());
});
}
}
}
Created a with 5 Thread pool of threads to execute corresponding tasks .
Use scenarios
CachedThreadPool The number of threads created is determined according to the amount of tasks in a short time , Therefore, it is suitable for processing scenarios with a large number of sudden tasks in a short time .
Executors.newSingleThreadExecutor(): Create a thread pool with only a single thread , It can ensure the order of first in, first out .
public class SingleThreadExecutorDemo {
public static void main(String[] args) {
// Creating a thread pool
ExecutorService threadPool = Executors.newSingleThreadExecutor();
// Perform tasks
for (int i = 0; i < 10; i++) {
int index = i;
threadPool.execute(() -> {
System.out.println(index + ": Task performed : " + Thread.currentThread().getName());
});
}
}
}
If you add a line of sleep statement to the printed statement , You will see the process that the output task is executed for each period of time ~
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Executors.newScheduledThreadPool(): Create a pool of threads that can perform deferred tasks .
public class ScheduledThreadPoolDemo {
public static void main(String[] args) {
// Creating a thread pool
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
// Add scheduled tasks (1s After execution )
System.out.println(" Add tasks , Time :" + new Date());
threadPool.schedule(() -> {
System.out.println(" Task performed , Time :" + new Date());
}, 2, TimeUnit.SECONDS);
}
}
Create a delay 2 The thread pool that executes tasks in seconds .
Executors.newSingleThreadScheduledExecutor(): Create a single threaded pool of threads that can perform deferred tasks . This thread pool can be seen as ScheduledThreadPool The single threaded version of .
public class SingleThreadScheduledExecutorDemo {
public static void main(String[] args) {
// Creating a thread pool
ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
// Add scheduled tasks (2s After execution )
System.out.println(" Add tasks , Time :" + new Date());
threadPool.schedule(() -> {
System.out.println(" Task performed , Time :" + new Date());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
}, 2, TimeUnit.SECONDS);
}
}
Executors.newWorkStealingPool(): Create a preemptive thread pool , The sequence of tasks is uncertain . It should be noted that this method is JDK 1.8 New version of , therefore 1.8 Cannot be used in programs before version .
public class WorkStealingPoolDemo {
public static void main(String[] args) {
// Creating a thread pool
ExecutorService threadPool = Executors.newWorkStealingPool();
// Perform tasks
for (int i = 0; i < 10; i++) {
final int index = i;
threadPool.execute(() -> {
System.out.println(index + " Be performed , The thread of :" + Thread.currentThread().getName());
});
}
// Make sure the task is done
while (!threadPool.isTerminated()) {
}
}
}
Attention should be paid to SingleThreadExecutor Comparison of thread pools for a single thread .
You can see , The order of task execution is not certain , Because this is a preemptive thread pool , Which task , Which task should be performed first .
ThreadPoolExecutor(): This is the most primitive , It is also the most recommended method to manually create a thread pool . Some properties can be customized when creating , For example, the number of core threads 、 Maximum number of threads, etc .
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
// Creating a thread pool
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
// Perform tasks
for (int i = 0; i < 10; i++) {
final int index = i;
threadPool.execute(() -> {
System.out.println(index + " Be performed , The thread of :" + Thread.currentThread().getName());
});
}
}
}
Create a 10 Core threads 、 The maximum number of threads is 10 Thread pool of . Please refer to : Seven parameters of thread pool _ A blog full of ugly people -CSDN Blog
This article references from :Java Of midcourse pool 7 Ways to create ! - Nuggets
边栏推荐
猜你喜欢
随机推荐
Literature learning (part98) -- pseudosupervised deep subspace clustering
SerializationException: Could not read JSON: Unrecognized token “xxx“
并发编程-----------集合
【干货】知识共享的障碍及解决方法
OC 设置图片圆角 图片不变形等问题
多线程常用类
一道数据库查询面试题
Advertisements inserted in solo articles are not displayed
Token
创建线程池的七种方式
Is it safe for Huatai to open an account online in 2022?
QT配置OpenCV(二):成功
【OAuth2】三、OAuth2配置解读
win7下在安装Oracle10g时出现【安装检测到系统的主 IP 地址是 DHCP 分配的地址】的错误的解决办法
【Oauth2】四、OAuth2AuthorizationRequestRedirectFilter
浙大《概率与数理统计》第四版证明随机变量X,Y的相关系数的绝对值小于1,及一些疑问
SQL 中delete与truncate的区别
用unshift向对象数组中添加一个元素
华泰证券在哪开户安全,手机可以吗
UISwitch OFF状态下默认颜色设置