当前位置:网站首页>Introduction to thread pool
Introduction to thread pool
2022-07-25 00:45:00 【New yanghaibo】
Importance of thread pool
What is a pool ?
Pools in software , It can be understood as planned economy
Why use thread pools ?
1. Creating threads repeatedly is expensive
2. Too many threads will take up too much memory
With a small number of threads —— Avoid taking up too much memory
Keep these threads working , And can perform tasks repeatedly —— Avoid life cycle loss
applications

Create and stop thread pools
Parameters of thread pool construction method

Add rules for threads

Characteristics of increasing and decreasing threads

Work queue
Common queue types
1. Direct handover :SynchronousQueue
2. Unbounded queue :LinkedBlockingQueue
3. Bounded queues :ArrayBlockingQueue
4. Delay queue :DelayedWorkQueue
Thread pools are created manually or automatically
Automatically create ( I.e. direct call JDK Encapsulated construction method )
1.newFixedThreadPool
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* demonstration newFixedThreadPool
* Fixed number of threads
*/
public class FixedThreadPoolTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; 0 < 1000 ;
i++){
executorService.execute(new Task());
}
}
}
// The task class
class Task implements Runnable{
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
disadvantages : Out of work queue , out of memory

2.newSingleThreadExecutor
package threadpool;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* demonstration newSingleThreadExecutor
* Only one thread
*/
public class SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 1000; i++) {
executorService.execute(new Task());
}
}
}
disadvantages : When request stacking , Take up a lot of memory
3.CachedThreadPool
Cacheable thread pool
characteristic : It has the function of automatically recycling redundant threads
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* demonstration newCachedThreadPool
* Cacheable threads
*/
public class CachedThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++) {
executorService.execute(new Task());
}
}
}

4.ScheduledThreadPool
Thread pool supporting timed and periodic task execution
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* demonstration newScheduledThreadPool
* Thread pool for periodic task execution
*/
public class ScheduledThreadPoolTest {
public static void main(String[] args) {
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);
// Delay 5 second
//threadPool.schedule(new Task(), 5, TimeUnit.SECONDS);
// At a certain frequency
threadPool.scheduleAtFixedRate(new Task(), 1, 3, TimeUnit.SECONDS);
}
}
5.workStealingPool yes JDK1.8 Added
This thread pool is very different from the previous one
The subtasks
steal , Each thread can cooperate before
4 Parameters of a thread pool construction method

How to create thread pool correctly
According to different business scenarios , Set thread pool parameters
such as : How much memory there is , Name the thread, etc
The number of threads in the thread pool is appropriate

The correct way to stop the thread pool
1、shutdown
It won't stop right away , After finishing the previous task , Just stop the thread pool
2、isShutdown
Judge whether the thread pool enters the stop state
3、isTerminated
Judge whether the thread pool is completely terminated
4、awaitTermination
Used to determine
All tasks are completed
It's time to wait
I was interrupted while waiting , Throw an exception
5、shutdownNow
Stop the thread pool immediately , Returns the set of tasks that have not been executed in the task queue
Pause and resume thread pool
There are too many tasks to refuse

4 Type of rejection policy
AbortPolicy
DiscardPolicy
DiscardOldestPolicy
CallerRunsPolicy
Hook method
package threadpool;
import java.sql.Time;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Create thread pool manually
* Demonstrate the hook function before and after the execution of each task
*/
public class PauseableThreadPool extends ThreadPoolExecutor {
private boolean isPaused;
private final ReentrantLock lock = new ReentrantLock();
private Condition unpaused = lock.newCondition();
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
// Hook function Check before performing the task
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
lock.lock();
try {
while (isPaused) {
unpaused.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// Pause method
private void pause() {
lock.lock();
try {
isPaused = true;
} finally {
lock.unlock();
}
}
// Recovery method
public void resume() {
lock.lock();
try {
isPaused = false;
unpaused.signalAll();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
PauseableThreadPool pauseableThreadPool = new PauseableThreadPool(10, 20, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
// Anonymous inner class Give the definition of the class while creating the instance , All this is done in one expression .
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(" I was executed ");
try {
// Prevent too fast
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for (int i = 0; i < 10000; i++) {
pauseableThreadPool.execute(runnable);
}
Thread.sleep(1500);
pauseableThreadPool.pause();
System.out.println(" The thread pool is suspended ");
Thread.sleep(1500);
pauseableThreadPool.resume();
System.out.println(" The thread pool has been restored ");
}
}
Considerations for using thread pools
Avoid tasks piling up
Avoid excessive increase in the number of threads
Check for thread leaks
边栏推荐
- Promtool Check
- EF core: self referencing organizational structure tree
- 2022 Henan Mengxin League game 2: Henan University of technology K - Rice
- Is qiniu Business School reliable? Is it safe to open Huatai account recommended by the lecturer
- UART
- 第三章 内核开发
- Number of palindromes in question 5 of C language deduction (two methods)
- Digital signal processing synthesis matlab design of dual tone multi frequency dialing system
- Two numbers that appear only once in the array
- Chapter III kernel development
猜你喜欢

自动化测试系列-Selenium三种等待详解

Why do I have to clean up data?
![[Bert] transformer/bert/attention interview questions and answers](/img/32/5d29ce8056df16211630c3384adcf4.png)
[Bert] transformer/bert/attention interview questions and answers

阿里 Seata 新版本终于解决了 TCC 模式的幂等、悬挂和空回滚问题
![[LeetCode周赛复盘] 第 83 场双周赛20220723](/img/db/c264c94ca3307d4363d3cf7f5d770b.png)
[LeetCode周赛复盘] 第 83 场双周赛20220723

Tencent low code platform is officially open source! You can drag and drop and generate mobile phone projects and PC projects! Get private benefits

Leetcode 1260. two dimensional grid migration: two solutions (k simulations / one step)

Uncaught typeerror: cannot read properties of null (reading 'append') solution
![[hero planet July training leetcode problem solving daily] 24th line segment tree](/img/ae/1f3288a99cb07fcbb1836357e0229a.png)
[hero planet July training leetcode problem solving daily] 24th line segment tree

What can testers do when there is an online bug?
随机推荐
Redis pipeline technology / partition
Notes on topic brushing (XXII) -- Dynamic Planning: basic ideas and topics
LeetCode_ 6124_ The first letter that appears twice
Leetcode 0123. the best time to buy and sell stocks III: dynamic programming + simulation in constant space
Number of palindromes in question 5 of C language deduction (two methods)
Grafana connection tdengine reports an error 535
Two numbers that appear only once in the array
2022 Henan Mengxin League game 2: Henan University of technology K - Rice
[mindspore ascend] [user defined operator] graph_ In mode, customize how to traverse tensor
Pain and happiness -nio programming
#648 (Div. 2)(A. Matrix Game、B. Trouble Sort、C. Rotation Matching)
494. Target sum · depth first search · knapsack problem
7.24 party notice
Solution to the shortest Hamilton path problem
[leetcode weekly replay] game 83 biweekly 20220723
Dynamic programming-01 knapsack rolling array optimization
进程的几种状态
Unity3d calls between different script functions or parameters
Internal network mapping port to external network
[mindspore ascend] [running error] graph_ In mode, run the network to report an error