zoukankan      html  css  js  c++  java
  • 多线程16--单例--懒汉模式和静态内部类形

    1. 懒汉双重检验

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

    2. 静态内部类

     1 public class InnerSingleton {
     2     
     3     private static class Singletion {
     4         private static Singletion single = new Singletion();
     5     }
     6     
     7     public static Singletion getInstance(){
     8         return Singletion.single;
     9     }
    10 }
    View Code
  • 相关阅读:
    软件工程个人作业01
    学习进度条
    课堂练习:增加信息
    JavaWeb学习-1
    构建之法阅读笔记02
    java笔记04: String的理解与运用
    java:凯撒密码
    java笔记3(动手动脑)
    Java学习笔记--异常
    Advice详解
  • 原文地址:https://www.cnblogs.com/bravolove/p/7953500.html
Copyright © 2011-2022 走看看