单例模式:实例化自己,且类中只能有一个实例,还要通过静态代码块实现给其他对象 提供这一实例
//单例类
public class SingertonClass{
//私有构造——方法
private SingertonClass(){};
//实例化单利模式方法——实例化自己
private static SingertonClass singer = new SingertonClass();
//通过静态代码块给其他对象提供这一实例
public static SingertonClass gotheway(){
return singer;
};
}
synchronized同步锁:锁线程,下一线程想要使用对象就必须等到该同步锁线程使用完对象才可以使用,效率低下但是安全
public class SingertonClass2{
//私有构造
private SingertonClass2(){};
//创建对象
private static SingertonClass2 singer = null;
private static SingertonClass2 gotheway(){
//等同于 synchronized private static SingertonClass2 gotheway
synchronized(SingertonClass2.class){
//同步锁下必须加判断,不然出现线程安全问题
if(singer==null){
singer = new SingertonClass2();
}
}
return singer;
}
}
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。



