//不能保证线程安全的懒汉模式
public class Singleton{
private static Singleton instance;
//构造函数
private Singleton(){
}
public static Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//保证了线程安全的懒汉模式
public class Singleton{
//声明一个静态变量
private static Singleton instance;
//构造函数
private Singleton(){
}
//加锁的函数
public static synchronzied Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//饿汉模式
public class Singleton{
private static Singleton instance;
static{
instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
//双重校验锁 懒汉模式
public class Singleton{
private volatile static Singleton_volatile instance=null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
synchronzied(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton{
private static Singleton instance;
//构造函数
private Singleton(){
}
public static Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//保证了线程安全的懒汉模式
public class Singleton{
//声明一个静态变量
private static Singleton instance;
//构造函数
private Singleton(){
}
//加锁的函数
public static synchronzied Singleton getInstance(){
//为空的话 构建一个
if(instance == null ){
instance = new Singleton();
}
return instance;
}
}
//饿汉模式
public class Singleton{
private static Singleton instance;
static{
instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
//双重校验锁 懒汉模式
public class Singleton{
private volatile static Singleton_volatile instance=null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
synchronzied(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}