单例模式

单例模式

  • 饿汉模式

private static HungrySingleton instance = new HungrySingleton();

public static HungrySingleton getInstance() {
return instance;
}

  • 类加载时直接创建单例对象,天生线程安全。

  • 懒汉模式

public class LazySingleton {
    private static LazySingleton instance;

    public static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

非线程安全,测试如下:

public class Person implements Runnable {
    private CountDownLatch latch;

    public Person(CountDownLatch latch) {
        this.latch = latch;
    }
    @Override
    public void run() {
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();
        hungrySingleton.output();
        latch.countDown();
    }
}
public class SingletonTest {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        long start = System.currentTimeMillis();
        System.out.println("starting...");
        for (int i = 0; i < 10; i++) {
            Person p = new Person(countDownLatch);
            Thread thread = new Thread(p);
            thread.start();
        }
        try {
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        long now = System.currentTimeMillis();
        System.out.println("cost: "+ (now-start)+" ms");
    }
}

结果如图:

starting...
LazySingleton@41672b2d
LazySingleton@64a0b27
LazySingleton@78814553
LazySingleton@620196ec
LazySingleton@994e424
LazySingleton@72460481
LazySingleton@65afe199
LazySingleton@4c630b0d
LazySingleton@32c3e0c4
LazySingleton@3ceef829
cost: 13 ms
  • 常用单例
    1) getInstance方法加同步
public class SyncLazySingleton {
    private static SyncLazySingleton instance;
    public static synchronized SyncLazySingleton getInstance() {
        if (instance == null) {
            instance = new SyncLazySingleton();
        }
        return instance;
    }
}

2)Double-Check

public class DoubleCheckLazySingleton {
    private static volatile DoubleCheckLazySingleton instance;
    public static DoubleCheckLazySingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckLazySingleton.class) {
                if (instance == null) {
                    instance = new DoubleCheckLazySingleton();
                }
            }
        }
        return instance;
    }
}

3)内部类(嵌套内部类,非普通内部类)

public class InnerClassSingleton {
    private static class LazyHolder {
        private static final InnerClassSingleton instance = new InnerClassSingleton();
    }

    public static InnerClassSingleton getInstance(){
        return LazyHolder.instance;
    }
}

待续。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值