zoukankan      html  css  js  c++  java
  • 多线程情况下,单例模式的实现方式

    方式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 }


  • 相关阅读:
    【2018.10.3】万圣节的快递
    【2018.10.3】万圣节的入场券
    【2018.10.2】纸条
    【2018.10.2】菌落合并
    【2018.10.2】Note of CXM
    【2018.10.1】【JSOI2016】最佳团体(bzoj4753)
    【2018.10.1】「JOI 2014 Final」年轮蛋糕
    【2018.9.26】K-D Tree详解
    Python中的numpy模块解析
    Python中xlrd模块解析
  • 原文地址:https://www.cnblogs.com/billmiao/p/9872206.html
Copyright © 2011-2022 走看看