Java单例模式

public class Person
{
  private static Person person=null;
  private Person(){}//将构造函数私有化
  public static Person GetPerson()
  {
    if(person!=null)
    {
      person=new Person();
    }
    return person;
  }
}

 懒汉式和饿汉式,区别就是在使用此单例类的时候,是否已经将单例初始化,如果已经初始化即为饿汉式。上例代码是懒汉式,是在调用了GetPerson才将单例给初始化。开发时一般用饿汉式(原因是可能因为懒汉式并发的问题)。

懒汉式单例  并发问题的解决方案:

class Single 
{
     private static Single s=null;  
     private Single(){}    
     public static  Single getInstance()
     {
           if(s==null)
            {
                  synchronized(Single.class)
                  {
                        if(s==null)
                        {
                               s=new Single();
                         }
                  }
            }
     }   
}        
原文地址:https://www.cnblogs.com/LJP-JumpAndFly/p/4675105.html