单例模式——多线程的线程池设计Java代码

以下是一个简单的Java代码示例,演示了如何使用单例模式来设计一个多线程的线程池:

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ThreadPoolSingleton {

private static ThreadPoolSingleton instance; private ExecutorService executorService; private ThreadPoolSingleton() { executorService = Executors.newFixedThreadPool(10);

}

public static synchronized ThreadPoolSingleton getInstance() {

if (instance == null) {

instance = new ThreadPoolSingleton();

}

return instance;

}

public synchronized ExecutorService getExecutorService() {

return executorService;

}}

在这个示例中,使用了单例模式来保证在整个应用程序中只有一个ThreadPoolSingleton实例。

使用getInstance()方法来获取这个实例。

在getInstance()方法中,如果instance为空,则创建一个新的ThreadPoolSingleton实例。在getExecutorService()方法中,我们返回executorService实例,供调用方使用。由于线程池是共享资源,因此我们在getInstance()方法和getExecutorService()方法中使用了synchronized关键字,以确保线程安全。

相关推荐
小二·几秒前
从零到上线:Spring Boot 3 + Spring Cloud Alibaba + Vue 3 构建高可用 RBAC 微服务系统(超详细实战)
vue.js·spring boot·微服务
cherry52305 分钟前
Java大厂面试真题:Spring Boot + 微服务 + 缓存架构三轮技术拷问实录
jvm·spring boot·mysql·微服务·java面试·分布式架构·redis缓存
code_std11 分钟前
SpringBoot 登录验证码
java·spring boot·后端
摇滚侠11 分钟前
Spring Boot3零基础教程,响应式编程,前景提要,笔记108
java·spring boot·笔记
java干货15 分钟前
BIO是“一人盯一桌”,NIO是“一人管全场”,AIO是“机器人送餐”
java·机器人·nio
Mos_x18 分钟前
@RestController注解
java·后端
迦蓝叶27 分钟前
使用 Apache Jena 构建 Java 知识图谱
java·apache·知识图谱·图搜索·关系查询·关系推理
学IT的周星星28 分钟前
Spring 框架整合 JUnit 单元测试
java·spring·junit·单元测试
bcbnb33 分钟前
Fiddler抓包工具使用教程,HTTPHTTPS抓包、代理配置与调试技巧全解析(附实战经验)
后端