java单例模式怎么做
1、第一种:懒汉模式。特点:到需要用的时候才实例化,实现了懒加载线程不安全代码如下:/** * 懒汉模式 */public class SingLetonLazy { private static SingLetonLazy instance; private SingLetonLazy(){ } public static SingLetonLazy getInstance(){ if(instance==null){ instance=new SingLetonLazy(); } return instance; }}

3、第三种:双重检查锁定懒汉模式。这种在效率上比第二种高一些,减少了第二种加锁的的范围。线程安全。/** * 懒汉模式 */public class SingLetonLazy { public static SingLetonLazy s=null; private SingLetonLazy() { //私有构造方法 } public static SingLetonLazy getSingLetonLazy() { if(s==null) { synchronized(SingLetonLazy.class) { if(s==null) { s=new SingLetonLazy();//实例化 } } } return s; }}

5、第五种:静态内部类实现懒汉模式。特点:借助内部类的静态语句块实现线程安全。/*** 懒汉模式*/public class SingLetonLazy { // 静态内部类 private static class NestClass { private static SingLetonLazy instance; static { instance = new SingLetonLazy(); } } // 不能直接new private SingLetonLazy() { } public static SingLetonLazy getSingLetonLazy() { return NestClass.instance; }}

7、第七步:测试。1、首先编写代码实现多线程2、将累计足够的线程然后同时触发创建类请求3、对比请求的类是否是同一个。