zoukankan      html  css  js  c++  java
  • 单例经典示例

    package com.etc.jichu;
    
    public class Singleton 
    {
    	//初始化为null的单例,用关键字volatile(不稳定的)修饰
    	private static volatile Singleton single=null;
    	//私有的构造方法
    	private Singleton(){}
    	public static Singleton getSingleton()
    	{
    		//如果当前实例为null则创建对象
    		if(single==null)
    		{
    			synchronized(Singleton.class)//1
    			{
    				if(single==null)//2
    				{
    					single=new Singleton();//3
    				}
    			}
    		}
    		return single;
    	}
    }
    /*
     * 线程 1 进入get 方法。
    由于single 为null,线程 1 在 //1 处进入 synchronized块。
    线程 1 被线程 2 预占。
    线程 2 进入get 方法。
    由于single 仍旧为null,线程 2 试图获取 //1 处的锁。然而,由于线程 1 持有该锁,线程 2 在 //1 处阻塞。
    线程 2 被线程 1 预占。
    线程 1 执行,由于在 //2 处实例仍旧为null,线程 1 还创建一个Singleton对象并将其引用赋值给single。
    线程 1 退出 synchronized块并从 get方法返回实例。
    线程 1 被线程 2 预占。
    线程 2 获取 //1 处的锁并检查single 是否为null。
    由于single 是非 null的,并没有创建第二个Singleton对象,由线程 1 创建的对象被返回。/
     */
    

      

  • 相关阅读:
    【Linux】命令——基本命令
    正则表达式
    Letex
    Markdown
    文本编辑器Vim
    【Linux】集群
    【Linux】软件安装
    共线性synteny
    windows触控手势
    【Linux】bin结尾的安装包
  • 原文地址:https://www.cnblogs.com/ipetergo/p/6243699.html
Copyright © 2011-2022 走看看