单例模式之懒汉与饿汉

1.饿汉式

package com.bjpowernode.singleModel;
//饿汉式
public class HungerMan {
    private HungerMan(){
        System.out.println(Thread.currentThread().getName()+"-->ok");
    }

    private final static HungerMan HUNGER=new HungerMan();
    public static HungerMan getInstance(){
        return HUNGER;
    }

    public static void main(String[] args) {
        for (int i=0;i<10;i++){
            new Thread(()->{
                System.out.println(getInstance());
            }).start();
        }
    }
}

2.懒汉式(三重锁机制)

package com.bjpowernode.singleModel;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//懒汉式
public class LazyMan {
    private static boolean flag=false;
    private LazyMan(){
        synchronized (LazyMan.class){
            if (flag==false){
                flag=true;
            }else{
                    throw new RuntimeException("不要试图发射破坏");
            }

        }
    }
    //与饿汉式不同:这里不要加final,后面要对其进行实例化。
    //防止指令重排,这里需添加特殊域变量volatile。
    /*指令重排现象:对象创建过程步骤错乱
    * 创建一个对象分三步:1.堆中分配内存空间
    *                   2.执行构造方法初始化对象参数
    *                   3.把这个对象指向内存空间
    * */
    private static volatile LazyMan lazyMan;
    public static LazyMan getInstance(){
        //此处须加类锁
        //若加对象锁,因为对象还未被创建,不存在锁,会报错NullPointException
        synchronized (LazyMan.class){
            if (lazyMan==null){
                lazyMan=new LazyMan();
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //LazyMan instance1 = LazyMan.getInstance();
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan instance2 = declaredConstructor.newInstance();
        LazyMan instance1 = declaredConstructor.newInstance();
        System.out.println(instance1);
        System.out.println(instance2);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值