单例模式:
1、懒汉式
package com.danli; /** * 懒汉式 * @author Administrator * */ public class User { private static User user = null; private User() {} synchronized public static User getUser() { if(user==null) { user = new User(); } return user; } }
package com.danli; /** * 线程 类 * @author Administrator * */ public class MyThread implements Runnable{ @Override public void run() { for(int i = 0;i<10;i++) { User user = User.getUser(); System.out.println(user); } } }
package com.danli; /** * 测试类 * @author Administrator * */ public class Main { public static void main(String[] args) { MyThread mt = new MyThread(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); Thread t4 = new Thread(mt); t1.start(); t2.start(); t3.start(); t4.start(); } }
测试示例:
2、饿汉式
package com.danli; /** * 饿汉式 * @author Administrator * */ public class User2 { private static final User2 user = new User2(); private User2() {} public static User2 getUser() { return user; } }
package com.danli; /** * 线程 类 * @author Administrator * */ public class MyThread implements Runnable{ @Override public void run() { for(int i = 0;i<10;i++) { User2 user = User2.getUser(); System.out.println(user); } } }
package com.danli; /** * 测试类 * @author Administrator * */ public class Main { public static void main(String[] args) { MyThread mt = new MyThread(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); Thread t4 = new Thread(mt); t1.start(); t2.start(); t3.start(); t4.start(); } }
结果示例:
3、枚举单例:
package com.enumsingle; /** * 枚举单例 * @author Administrator * */ public class Single{ //私有化无参构造 private Single(){} //创建静态获取实例方法getInstance() public static Single getInstance(){ return EnumSingle.INSTANCE.getInstance(); } private static enum EnumSingle{ INSTANCE; //私有化实例对象 private Single single; //通过枚举类无参构造方法创建对象 private EnumSingle(){ single = new Single(); } public Single getInstance(){ return single; } } }
package com.enumsingle; /** * 线程 类 * @author Administrator * */ public class MyThread implements Runnable{ @Override public void run() { for(int i = 0;i<10;i++) { Single es = Single.getInstance(); System.out.println(es); } } }
package com.enumsingle; /** * 测试类 * @author Administrator * */ public class Main { public static void main(String[] args) { MyThread mt = new MyThread(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); Thread t4 = new Thread(mt); t1.start(); t2.start(); t3.start(); t4.start(); } }
结果示例