/**
* 单例模式,多个线程获取到的是同一个对象
* @author pipi
*
*/
public class SingletonTest {
public static void main(String[] args) {
for(int i = 0;i < 2;i++){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(A.getInstance());
System.out.println(B.getInstance());
}
}).start();
}
}
}
/**
* 饱汉模式
* @author pipi
*
*/
class A{
private static A a = new A();
private A(){}
public static A getInstance(){
return a;
}
}
/**
* 饥汉模式
* @author pipi
*
*/
class B{
private static B b = null;
private B(){}
public synchronized static B getInstance(){
if(b == null)
b = new B();
return b;
}
}
设计模式之单例模式
最新推荐文章于 2025-12-16 20:04:55 发布
本文介绍了单例模式的两种实现方式:饱汉模式和饥汉模式。通过实例代码演示了如何确保多个线程环境下只创建一个实例,展示了不同模式下单例对象的创建时机及其对线程安全性的处理。
101万+

被折叠的 条评论
为什么被折叠?



