/**
* 方法一
* 单例模式的实现:饿汉式,线程安全 但效率比较低
*/
public class SingletonTest {
// 定义一个私有的构造方法
private SingletonTest() {
}
// 将自身的实例对象设置为一个属性,并加上Static和final修饰符
private static final SingletonTest instance = new SingletonTest();
// 静态方法返回该类的实例
public static SingletonTest getInstancei() {
return instance;
}
}
/**
*方法二
* 单例模式的实现:饱汉式,非线程安全
*
*/
public class SingletonTest {
// 定义私有构造方法(防止通过 new SingletonTest()去实例化)
private SingletonTest() {
}
// 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)
private static SingletonTest instance;
// 定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题)
public static SingletonTest getInstance() {
if (instance == null)
instance = new SingletonTest();
return instance;
}
}
/**
*方法三
* 单例模式的实现:饱汉式,线程安全简单实现
*
*/
public class SingletonTest {
// 定义私有构造方法(防止通过 new SingletonTest()去实例化)
private SingletonTest() {
}
// 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)
private static SingletonTest instance;
// 定义一个静态的方法(调用时再初始化SingletonTest,使用synchronized 避免多线程访问时,可能造成重的复初始化问题)
public static synchronized SingletonTest getInstance() {
if (instance == null)
instance = new SingletonTest();
return instance;
}
}
/**
* 方法四
* 单例模式最优方案
* 线程安全 并且效率高
*
*/
public class SingletonTest {
// 定义一个私有构造方法
private SingletonTest() {
}
//定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
private static volatile SingletonTest instance;
//定义一个公有的静态方法,返回该类型实例
public static SingletonTest getIstance() {
// 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率)
if (instance == null) {
//同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
synchronized (SingletonTest.class) {
//未初始化,则初始instance变量
if (instance == null) {
instance = new SingletonTest();
}
}
}
return instance;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有