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

    用于创建单一类。例如一些工具类等。

    主要有以下四种实现:

    lazy load,线程不安全

     1 public class UnsafeLazySingleton {
     2 
     3     private static UnsafeLazySingleton instance;
     4 
     5     private UnsafeLazySingleton() {
     6     }
     7 
     8     public static UnsafeLazySingleton getInstance() {
     9         if (instance == null) {
    10             instance = new UnsafeLazySingleton();
    11         }
    12         return instance;
    13     }
    14 }

    lazy load,线程安全,但是每次获取需要锁,效率较差

     1 public class SafeLazySingletonWithLock {
     2 
     3     private static SafeLazySingletonWithLock instance;
     4 
     5     private SafeLazySingletonWithLock() {
     6     }
     7 
     8     public static synchronized SafeLazySingletonWithLock getInstance() {
     9         if (instance == null) {
    10             instance = new SafeLazySingletonWithLock();
    11         }
    12         return instance;
    13     }
    14 }

    线程安全

     1 public class UnLazySingleton {
     2 
     3     private static UnLazySingleton instance = new UnLazySingleton();
     4 
     5     private UnLazySingleton() {
     6     }
     7 
     8     public static UnLazySingleton getInstance() {
     9         return instance;
    10     }
    11 }

    双检索

     1 public class DoubleCheckedSingleton {
     2 
     3     private volatile static DoubleCheckedSingleton singleton;
     4 
     5     private DoubleCheckedSingleton() {
     6     }
     7 
     8     public static DoubleCheckedSingleton getSingleton() {
     9         if (singleton == null) {
    10             synchronized (DoubleCheckedSingleton.class) {
    11                 if (singleton == null) {
    12                     singleton = new DoubleCheckedSingleton();
    13                 }
    14             }
    15         }
    16         return singleton;
    17     }
    18 }

    推荐最后一种方式,即实现了lazy load,又是线程安全,并且只有在初次加载并发的时候需要锁,其他时候不会用到锁,效率也有保障。PS:首次并发的时候出现冲突,都运行到代码10,当一个线程成功初始化后,由于单例是volatile修饰的,其他线程可见,代码11判断后不会发生重复定义,保证线程安全。

  • 相关阅读:
    sqlhelper使用指南
    大三学长带我学习JAVA。作业1. 第1讲.Java.SE入门、JDK的下载与安装、第一个Java程序、Java程序的编译与执行 大三学长带我学习JAVA。作业1.
    pku1201 Intervals
    hdu 1364 king
    pku 3268 Silver Cow Party
    pku 3169 Layout
    hdu 2680 Choose the best route
    hdu 2983
    pku 1716 Integer Intervals
    pku 2387 Til the Cows Come Home
  • 原文地址:https://www.cnblogs.com/avalon-merlin/p/10522378.html
Copyright © 2011-2022 走看看