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 }


  • 相关阅读:
    Exercise02_09
    Exercise02_05
    Exercise02_01
    Exercise02_03
    Exercise02_07
    web.xml配置详解
    面对不成功的人生
    请不以结婚为目的的恋爱吧
    年轻人能为世界做点什么
    不作就不会活
  • 原文地址:https://www.cnblogs.com/billmiao/p/9872206.html
Copyright © 2011-2022 走看看