当前位置:网站首页>并发模式之单例和不变模式
并发模式之单例和不变模式
2022-07-29 02:19:00 【程序猫大刚】
单例模式
单例模式是为了确保系统中某个类只存在一个实例。
在多种写法中,推荐使用静态内部类方式,利用类加载一次特性确保只有一个实例(线程安全),
同时具备无锁和懒创建优点。
示例:
public class StaticInnerClassSingleton {
// 私有化构造方法
private StaticInnerClassSingleton(){}
// 内部类
static class Holder{
static StaticInnerClassSingleton INSTANCE = new StaticInnerClassSingleton();
}
// 获取实例对象
public static StaticInnerClassSingleton getInstance(){
return Holder.INSTANCE;
}
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(()->{
System.out.println(StaticInnerClassSingleton.getInstance());
}).start();
}
}
}
不变模式
在并发场景中,不变对象是不需要同步操作的。(因为对象不会改变,所以多个线程访问不会出现不一致问题)
特征:
- class被修饰为final
- 属性是私有且被final修饰的
JDK中所有的元数据类、包装类都是使用不变模式实现的。
java.lang.String
java.lang.Boolean
java.lang.Byte
java.lang.Character
java.lang.Double
java.lang.Float
java.lang.Integer
java.lang.Long
java.lang.Short
例子:
public final class FinalCat {// final 确保无子类
private final String name;// final 确保属性
private final Integer age;
public FinalCat(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return "FinalCat{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
FinalCat cat = new FinalCat("皮侃子", 4);
System.out.println(cat);
}
}
边栏推荐
猜你喜欢

Code implementation - the greatest common factor of polynomials (linear algebra)

Understand the evolution of redis architecture in one article

Library management system

ES6 detailed quick start!

关于时间复杂度的一些新认识

Introduction to network foundation

Source code of Jiugongge heart puzzle Applet / source code of main wechat applet with traffic

【报错】node:internal/modules/cjs/loader:936 【解决方法】

PHP幸运抽奖系统带后台源码
![[error reporting] node:internal/modules/cjs/loader:936 [solution]](/img/73/849c58c814c1a47dff0cde0e365c75.png)
[error reporting] node:internal/modules/cjs/loader:936 [solution]
随机推荐
NVIDIA-VPI(Vision Programming Interface)
Three expiration strategies
C语言:小乐乐与进制转换
QT screen adaptive automatic layout, drag the window to automatically grow larger and smaller (I)
Introduction to network foundation
etcd实现大规模服务治理应用实战
10.书写规则-文件搜寻
Stm32f103xx firmware function library-1
php 进程通信系列 (一) 命名管道
Source code and display of 18 classic programs in C language vs2019
MPEG音频编码三十年
Kbxxxxx is not necessarily a patch, but also a description of a solution to a problem
New conch movie theme template m3.1 fully decrypted version multifunctional apple cmsv10 background adaptive theme open source fully decrypted version
CUDA details GPU architecture
Explanation of engineering economics terms
ROCBOSS开源微社区轻论坛类源码
Three implementation methods of Servlet
DHCP协议详细解析
FPGA skimming memory (Verilog implementation of ram and FIFO)
自组织是管理者和成员的双向奔赴