【面试】字节跳动提前批笔试题:实现三种线程安全的单例模式

饿汉模式

  • 线程安全,调用效率高,但是不能延时加载:

public class hungery {
	//类初始化时立即加载对象(没有延迟加载的优势),天然的线程安全
	private static hungery instance=new hungery();
	private hungery(){};
	//方法没有同步,调用效率高
	public static hungery getinstance(){
		return instance;
	}
	public static void main(String[] args) {
		hungery instance2=new hungery();
		System.out.print(instance2.getinstance()==hungery.instance);
	}

}

懒汉模式

  • 线程安全,调用效率不高,但是能延时加载:
public class lazymodel {
	private static lazymodel singleton=null;
    //懒汉式 synchronized锁方法实现
	public static synchronized lazymodel getinstance(){
		if(singleton==null){
			singleton=new lazymodel();
		}
		return singleton;
	} 
	public static void main(String[] args) {
		lazymodel instance2=new lazymodel();
		System.out.print(instance2.getinstance()==lazymodel.getinstance());
	}
}

双重检测锁模式

  • 由于JVM底层模型原因,偶尔会出问题,不建议使用

public class duplicationcheck {
	  /*
                         懒汉式  双重检查锁
     */
    //volatile保证可见性,读值需要访问主内存
	private static volatile duplicationcheck Single=null;
	public duplicationcheck getSingle(){
		if(Single==null){
			synchronized(duplicationcheck.class){
				//原子性,可见性
				if(Single==null){
					Single=new duplicationcheck();
				}
			}
		}
		return Single;
	}
	public static void main(String[] args) {
		duplicationcheck single=new duplicationcheck();
		System.out.print(single.getSingle()==new duplicationcheck().getSingle());
	}
}

附另外两种

  • 静态内部类式(线程安全,调用效率高,可以延时加载)

public class LazyIner {
    /*
    懒汉式 静态内部类实现
     */
	public static class getsinglen{
		static LazyIner  LazyIner=new LazyIner();
	}
	public static void main(String[] args) {
		System.out.println(getsinglen.LazyIner == getsinglen.LazyIner);

	}
}
  • 枚举类(线程安全,调用效率高,不能延时加载,可以天然的防止反射和反序列化调用)
public enum LazyEnum {
	INSTANCE;
}

在另一个main方法中调用

		System.out.print(LazyEnum.INSTANCE==LazyEnum.INSTANCE);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值