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 创建的对象被返回。/
     */
    

      

  • 相关阅读:
    在 Spring 中使用 Quartz
    Quartz 快速进阶
    任务调度概述
    Spring Boot 2.x 整合 Mybatis 3.x
    pwd函数实现
    07-图4 哈利·波特的考试 (25 分)
    06-图3 六度空间 (30 分)
    linux中的目录
    Linux中的文件
    06-图2 Saving James Bond
  • 原文地址:https://www.cnblogs.com/ipetergo/p/6243699.html
Copyright © 2011-2022 走看看