• 多线程情况下,单例模式的实现方式


    方式1(推荐)

     1 package singleton;
     2 
     3 public class Singletion {
     4     
     5     private static class InnerSingletion {
     6         private static Singletion single = new Singletion();
     7     }
     8     
     9     public static Singletion getInstance(){
    10         return InnerSingletion.single;
    11     }
    12     
    13 }

    方式2(double check)

     1 package singleton;
     2 
     3 public class DubbleSingleton {
     4 
     5     private static DubbleSingleton ds;
     6     
     7     public  static DubbleSingleton getDs(){
     8         if(ds == null){
     9             try {
    10                 //模拟初始化对象的准备时间...
    11                 Thread.sleep(3000);
    12             } catch (InterruptedException e) {
    13                 e.printStackTrace();
    14             }
    15             synchronized (DubbleSingleton.class) {
    16                 if(ds == null){
    17                     ds = new DubbleSingleton();
    18                 }
    19             }
    20         }
    21         return ds;
    22     }
    23     
    24     public static void main(String[] args) {
    25         Thread t1 = new Thread(new Runnable() {
    26             @Override
    27             public void run() {
    28                 System.out.println(DubbleSingleton.getDs().hashCode());
    29             }
    30         },"t1");
    31         Thread t2 = new Thread(new Runnable() {
    32             @Override
    33             public void run() {
    34                 System.out.println(DubbleSingleton.getDs().hashCode());
    35             }
    36         },"t2");
    37         Thread t3 = new Thread(new Runnable() {
    38             @Override
    39             public void run() {
    40                 System.out.println(DubbleSingleton.getDs().hashCode());
    41             }
    42         },"t3");
    43         
    44         t1.start();
    45         t2.start();
    46         t3.start();
    47     }
    48     
    49 }


  • 相关阅读:
    根据数据库表字段动态生成选择画面
    ABAP中字符串处理方法小结(二)
    如何获取汉字字符串长度
    如何强制分页-[NEW-PAGE]
    如何设置输出颜色-[FORMAT..COLOR..]
    ◆◆0如何取得字符串最后一位
    VALSE2019
    pycharm使用总结
    生活经验
    爱情存在吗-3
  • 原文地址:https://www.cnblogs.com/billmiao/p/9872206.html
Copyright © 2020-2023  润新知