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

    懒汉模式线程不安全:

    package com.ddy.singleton;
    public class Singleton {
    private static Singleton instance;
    private Singleton(){
    }
    public static Singleton getInstance(){
    if(instance == null){
    instance = new Singleton();
    }
    return instance;
    }
    }
    package com.ddy.singleton;
    public class Service1 implements Runnable {
    private Singleton singleton = null;
    //public Set<Singleton> singles = new HashSet<>();  
    @Override
    public void run() {
    // TODO Auto-generated method stub
    singleton = Singleton.getInstance();
    System.out.println(singleton+","+Thread.currentThread().getName());
    }
    }
    package com.ddy.singleton;
    public class Test {
    public static void main(String[] args) throws InterruptedException {
    Service1 t1 = new Service1();
    Service1 t2 = new Service1();
    new Thread(t1).start();
    new Thread(t2).start();
    }
    }

    输出结果不一致 ,说明线程不安全

    修改如下:

    package com.ddy.singleton;
    public class Singleton {
    private static Singleton instance;
    private Singleton(){
    }
    public static Singleton getInstance(){
    if(instance == null){
    synchronized (Singleton.class){
    if (instance == null) {                 //Double Checked
                   instance = new Singleton();
               }
    }
    }
    return instance;
    }
    }
    这样就做到线程安全了
  • 相关阅读:
    iOS去除导航栏和tabbar的横线
    各种坑
    iOS系统消息
    文件的读写
    MAC机中安装ruby环境--转载
    一句话处理服务器头像的尺寸
    开一个线程来处理 耗时的操作
    angular2中一种换肤实现方案
    一句话说明==和equals的区别
    下拉框样式在不同浏览器的简单兼容
  • 原文地址:https://www.cnblogs.com/vincent4code/p/5935295.html
Copyright © 2011-2022 走看看