JAVA单例模式:懒汉式,饿汉式
生活随笔
收集整理的这篇文章主要介绍了
JAVA单例模式:懒汉式,饿汉式
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
今天复习了一下java的单例模式,写了懒汉式和饿汉式的实现例子。代码如下:
1.懒汉式单例
package com.lf.shejimoshi;/*** @classDesc: 类描述:(懒汉式单例测试类) * @author baobaolan* @createTime 2018年1月10日 * @version v1.0*/ public class SingletonTest {/*** @functionDesc: 功能描述:(测试懒汉式单例模式) * @author baobaolan* @createTime 2018年1月10日 * @version v1.0*/public static void main(String[] args) {Student s1 = Student.getStudent();Student s2 = Student.getStudent();System.out.println(s1==s2);} }/*** @classDesc: 类描述:(学生类) * @author baobaolan* @createTime 2018年1月10日 * @version v1.0*/ class Student{//定义全局变量private static Student student;//私有化构造函数private Student(){}/*** @functionDesc: 功能描述:(对外暴露方法) * @author baobaolan* @createTime 2018年1月10日 * @version v1.0*/public static Student getStudent(){if(student==null){//加上同步锁,保证线程安全synchronized(Student.class){student = new Student();}}return student;} }
2.饿汉式单例
package com.lf.shejimoshi;/*** @classDesc: 类描述:(测试类) * @author baobaolan* @createTime 2018年1月10日 * @version v1.0*/ public class Singleton2Test {public static void main(String[] args) {Teacher teacher1 = Teacher.getTeacher();Teacher teacher2 = Teacher.getTeacher();System.out.println(teacher1==teacher2);}}/*** @classDesc: 类描述:(饿汉式单例) * @author baobaolan* @createTime 2018年1月10日 * @version v1.0*/ class Teacher{//类加载的时候初始化一次private static final Teacher teacher = new Teacher();//私有化构造函数private Teacher(){super();}/*** @functionDesc: 功能描述:(对外暴露的方法) * @author baobaolan* @createTime 2018年1月10日 * @version v1.0*/public static Teacher getTeacher(){return teacher;}}
3.总结
懒汉式线程不安全,需要加上同步锁,同步锁影响了程序执行效率。
饿汉式天生线程安全,类加载的时候初始化一次对象,效率比懒汉式高。
转载于:https://www.cnblogs.com/leifei/p/8258949.html
与50位技术专家面对面20年技术见证,附赠技术全景图总结
以上是生活随笔为你收集整理的JAVA单例模式:懒汉式,饿汉式的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: hystrix总结之多返回值命令
- 下一篇: nginx+ssl+pm2 部署 nod