zoukankan      html  css  js  c++  java
  • 单例模式

    懒加载,线程不安全 
    1. public class Singleton {
    2. private static Singleton instance;
    3. private Singleton(){}
    4. public static Singleton getInstance(){
    5. if(instance == null){
    6. instance = new Singleton();
    7. }
    8. return instance;
    9. }
    10. }
    懒加载,线程安全,线程方法排序
    1. public class Singleton {
    2. private static Singleton instance;
    3. private Singleton(){}
    4. public static synchronized Singleton getInstance(){
    5. if(instance == null){
    6. instance = new Singleton();
    7. }
    8. return instance;
    9. }
    10. }
    synchronized表示多线程排序执行方法。
    懒加载,线程安全,线程属性传递
    1. public class Singleton {
    2. private volatile static Singleton instance;
    3. private Singleton(){}
    4. public static Singleton getInstance(){
    5. if(instance == null){
    6. instance = new Singleton();
    7. }
    8. return instance;
    9. }
    10. }
    volatile表示变量修改最后的值。
    类加载,线程安全
    1. public class Singleton {
    2. private static Singleton instance = new Singleton();
    3. private Singleton(){}
    4. public static Singleton getInstance(){
    5. return instance;
    6. }
    7. }
    静态内部类加载,线程安全
    1. public class Singleton {
    2. private static class SingletonHolder{
    3. private static final Singleton INSTANCE = new Singleton();
    4. }
    5. private Singleton(){}
    6. public static Singleton getInstance(){
    7. return SingletonHolder.INSTANCE;
    8. }
    9. }
    枚举
    1. public enum Singleton {
    2. INSTANCE;
    3.    private Single(){}
    4. public void whateverMethod(){}
    5. }






  • 相关阅读:
    bfs两种记录路径方法
    次小生成树
    2018 ICPC 区域赛 焦作场 D. Keiichi Tsuchiya the Drift King(计算几何)
    数组分组
    POJ
    数位DP详解
    2018ICPC青岛 E
    HDU
    Google工程师打造Remix OS系统 桌面版安卓下载
    使用angular封装echarts
  • 原文地址:https://www.cnblogs.com/RocketMan/p/6400139.html
Copyright © 2011-2022 走看看