黑马程序员技术交流社区
标题:
懒汉式和饿汉式单例模式
[打印本页]
作者:
哈皮哈皮doge
时间:
2015-8-25 22:53
标题:
懒汉式和饿汉式单例模式
本帖最后由 哈皮哈皮doge 于 2015-8-25 23:06 编辑
/*
* 2种常见的单例模式:懒汉式和饿汉式
* 懒汉式:用到该对象才new,存在线程不安全的问题
* 饿汉式:管你用不用,上来就new,推荐使用
*/
/*
* 1.饿汉式
*/
class Singleton1{
private static Singleton1 instance = new Singleton1();//1.jvm加载class的时候就初始化instance变量,static同时保证只有一个该类的实例
private Singleton1(){}//2.构造方法的访问权限设为private,保证了在该类的外部无法创建该类的实例
public static Singleton1 getInstance(){//3.对外提供获得该实例的方法
return instance;
}
}
/*
* 2.懒汉式
*/
class Singleton2{
private static Singleton2 instance = null;
private Singleton2(){}
public static Singleton2 getInstance(){
if(instance==null){
instance = new Singleton2();//在多线程环境下,可能会创建多个对象,每个线程将instance的值保存到各自的线程栈中,独立操作
}
return instance;
}
}
/*
* 解决懒汉式线程不同步问题
*/
class Singleton3{
private static Singleton3 instance = null;
private Singleton3(){}
public static Singleton3 getInstance(){
if(instance==null){
//1.getInstance()属于静态同步方法,所以锁是当前对象的Class对象
//2.对于实例同步方法,锁是当前对象
//3.对于同步方法块,锁是Synchonized括号里配置的对象
synchronized (Singleton3.class) {//当线程执行到此处的时候发现锁是lock的(即被其他线程占用着),于是等待,等到其他线程释放锁后,再执行到此时,发现instance已经创建了,于是就不会再创建了
if(instance==null){
instance = new Singleton3();
}
}
}
return instance;
}
}
复制代码
作者:
Cancer
时间:
2015-8-25 23:05
挺楼主,好多没看懂
作者:
哈皮哈皮doge
时间:
2015-8-25 23:07
Cancer 发表于 2015-8-25 23:05
挺楼主,好多没看懂
个人理解,一起交流
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2