当前位置:网站首页>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
边栏推荐
- 2012.4.13 360 written examination summary
- WPF implements RichTextBox keyword query highlighting
- 2022 Henan Mengxin League game 2: Henan University of technology K - Rice
- Improve static loading dynamic loading
- js && ||
- NFT chain game system development metauniverse gamefi construction
- Why do I have to clean up data?
- Use es to realize fuzzy search and search recommendation of personal blog
- Detailed explanation of the usage of vector, queue and stack
- Heap and stack in embedded development
猜你喜欢

Soft test --- fundamentals of programming language (Part 2)

Why do I have to clean up data?

Moonpdflib Preview PDF usage record

阿里 Seata 新版本终于解决了 TCC 模式的幂等、悬挂和空回滚问题

Wechat applet development learning 5 (custom components)

Financial RPA robot enables enterprises to open a new era of intelligence

Unity panel control

动态规划-01背包滚动数组优化

2022 Henan Mengxin League game 2: Henan University of technology K - Rice

Install software on kubernetes cluster using helm 3 package manager
随机推荐
Use es to realize fuzzy search and search recommendation of personal blog
数组中只出现一次的两个数字
Click the "native practice" search box to expand the special effect so that you can realize it. How will you realize it?
UART
Fast development board for Godson solid state drive startup (burning system to solid state) - partition
Detailed usage of iperf
Measurement and Multisim Simulation of volt ampere characteristics of circuit components (engineering documents attached)
px rem em
asp adodb.stream对象的方法属性
Does opengauss support using Sqlalchemy connections?
BGP机房和BGP
Principle of data proxy
Unity slider slider development
Add the two numbers in the linked list of the second question of C language. Ergodic method
Pain and happiness -nio programming
[mindspore ascend] [user defined operator] graph_ In mode, customize how to traverse tensor
unresolved external symbol [email protected] resolvent
分页的相关知识
Uxdb resets the password without knowing the plaintext password
Grafana connection tdengine reports an error 535