当前位置:网站首页>Implement a thread pool
Implement a thread pool
2022-07-31 09:32:00 【Master_hl】
1.线程池是什么?
线程池,字面意思来说,Somewhat similar to our string constant pool,数据库连接池等等.
1.1 Why the introduction of the concept of a thread pool??
This is from the introduction of thread,,
The process itself can already do 并发编程了,Why have a thread??The process is too weight,High cost of creation and destruction are(需要申请、释放资源),The thread is optimized for the above problem(The same process of threads share the same set of system resources)
虽然如此,But in more frequently create、Release resources scenarios,Thread is a little carry not to live!!
所以,进一步优化,就引入了线程池.The purpose of existence of thread pool,In order to let the program apes don't have to create a new thread,Direct use of the existing thread wants to work can!!
【线程池解决问题的思路】
After the threads created,放到池子里,需要使用线程,Directly from the pool,Rather than through the system to create.当线程用完了,And sent back to the pool,Rather than through the system to destroy!!
1.2 Why put the thread in the pool,From the pool threads than from here to create a thread system of high efficiency??
1.从池子里取,Is pure user mode operation.
2.Through the system to create,Involves the kernel operation.
And we usually think that,Be involved in kernel mode operation,Than pure user mode of inefficient operation!!Combining with the below scenarios to understand

2.标准库中的线程池
1.使用 Executors.newFixedThreadPool(10) 能创建出固定包含 10 个线程的线程池.
2.返回值类型为 ExecutorService3.通过 ExecutorService.submit 可以注册一个任务到线程池中.
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for(int i = 0; i < 100; i++) {
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
});
}
}注意这行代码:
ExecutorService threadPool = Executors.newFixedThreadPool(10);newFixedThreadPool 是 Executors 类的一个静态方法,Using static method to create instances like this,这样的方法,称为"工厂方法",对应的设计模式,就叫做"工厂模式".
通常情况下,创建对象,是借助 new ,Call the constructor to implement.但是 Java 里面的构造方法,有诸多限制,Most of the time is not convenient to use,So you need to packing layer structure method,The outer packing effect is the factory method!!
Why construction method sometimes is not convenient to use??
Construction method of limit is,The constructor name must is as same as the name of the class.If you want to achieve different versions of the structure,Have to by overloading,But the overloading and requires the parameter type and the number of different.When we are of the same scene is just the parameter types and parameters have the same number,Overloading is doesn't work!!请看以下例子:
When I need to use the structure side said two points:A cartesian coordinate system,构造点;One is the polar coordinates structure point.
class Point {
// 笛卡尔坐标系,构造点
public Point(double x, double y) { };
// 使用极坐标系,构造点
public Point(double r, double a) { };
// Error : 编译错误
}
显然,这段代码编译错误,Do not conform to the overloaded rules,At this time we will need to use the factory pattern to solve the above problem.
class Point {
// 笛卡尔坐标系,构造点
public static Point makePointByXY(double x, double y) {
Point point = new Point();
point.setX(x);
point.setY(y);
return point;
}
// 极坐标系,构造点
public static Point makePointByRA(double r, double a) {
Point point = new Point();
point.setR(r);
point.setA(a);
return point;
}
}So then instantiated only need by the name of the class call the static method can create!!
Executors 创建线程池的几种方式:
1.newFixedThreadPool: 创建固定线程数的线程池2.newCachedThreadPool: 创建线程数目动态增长的线程池.3.newSingleThreadExecutor: 创建只包含单个线程的线程池.4.newScheduledThreadPool: 设定 延迟时间后执行命令,或者定期执行命令. 是进阶版的Timer.
Executors The inside of the factory methods,其实都是针对 ThreadPoolExecutor This class has carried on the new And into the parameter of different style,To achieve different kinds of thread pool in the structure!!
3.实现线程池
class MyThreadPool {
// 这个队列就是 "任务队列" The current thread to complete the tasks into the queue
// Again by the inside of the thread pool worker thread responsible for completing them!!
private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
// 核心方法,Insert into the thread pool
public void submit(Runnable runnable) {
try {
queue.put(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// n : Set several threads in thread pool
public MyThreadPool(int n) {
// In the constructor will need to create some threads,Let the thread responsible for performing the above insert tasks
for(int i = 0; i < n; i++) {
Thread t = new Thread(() -> {
while(!Thread.currentThread().isInterrupted()) {
try {
// 取出任务,直接执行
Runnable runnable = queue.take();
runnable.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
}
public class TestDemo3 {
public static void main(String[] args) {
// 10 Threads execute together 100 个任务
MyThreadPool myThreadPool = new MyThreadPool(10);
for(int i = 0; i < 100; i++) {
myThreadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
});
}
}
}
The realization of the thread pool than the timer,要简单太多了!!
【基本步骤】
1.核心操作为 submit,将任务加入线程池中;
2.使用一个 BlockingQueue 组织所有的任务;
3.每个线程,不停的从 BlockingQueue In the quests and perform can.
本篇博客就到这里了,谢谢观看!!
边栏推荐
猜你喜欢

来n遍剑指--07. 重建二叉树

开放麒麟 openKylin 自动化开发者平台正式发布

作为面试官,关于线程池的问题我一般这样套路...

loadrunner-controller-目标场景Schedule配置

文件管理:目录管理

Spark 在 Yarn 上运行 Spark 应用程序

Kotlin—基本语法(二)

浓眉大眼的谷歌 Chrome 也叛变了,教你一招快速清除其自带广告

Gradle series - Groovy overview, basic use (based on Groovy document 4.0.4) day2-1
![[NLP] Interpretation of Transformer Theory](/img/5f/8e1b9e48310817a0443eb445479045.png)
[NLP] Interpretation of Transformer Theory
随机推荐
qt pass custom structure parameters in different threads
安装gnome-screenshot截图工具
js radar chart statistical chart plugin
服务器上解压文件时提示“gzip: stdin: not in gzip format,tar: Child returned status 1,tar: Error is not recovera“
使用turtle画按钮
如何将亚马逊广告添加到您的 WordPress 网站(3 种方法)
loadrunner录制问题
spark过滤器
JSP exception对象简介说明
Flink1.15源码阅读——PER_JOB vs APPLICATION执行流程
各位大佬,sqlserver 支持表名正则匹配吗
matlab常用符号用法总结
【NLP】Transformer理论解读
JSP pagecontext对象的简介说明
&#x开头的是什么编码?
js雷达图统计图表插件
刷题《剑指Offer》day05
MySQL 高级(进阶) SQL 语句 (一)
感情危机,朋友的网恋女友要和他闹分手,问我怎么办
优信年营收16亿:亏损3亿 已与蔚来资本及58集团签署股权协议