单例模式——多线程的线程池设计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关键字,以确保线程安全。

相关推荐
止语Lab1 小时前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
小码哥_常2 小时前
Spring Boot一键限速:守护你的接口“高速路”
后端
HoneyMoose2 小时前
Jenkins Cloudflare 部署提示错误
java·servlet·jenkins
阿丰资源2 小时前
基于SpringBoot的物流信息管理系统设计与实现(附资料)
java·spring boot·后端
Predestination王瀞潞2 小时前
Java EE3-我独自整合(第四章:Spring bean标签的常见配置)
java·spring·java-ee
overmind2 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
资深数据库专家2 小时前
总账EBS 应用服务器1 的监控分析
java·网络·数据库
房开民2 小时前
可变参数模板
java·开发语言·算法
t***5442 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_2 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode