三种单例模式的实现方式
2014-04-22 15:47
148 查看
本示例主要演示了三种单例模式的实现方式,并对各种实现方式的优缺点进行比较。
1,静态变量直接创建单例对象,
2,延迟加载, 由于要保证线程安全,使用了synchronized来保证创建过程的线程同步
3,使用内部类
View Code
1,静态变量直接创建单例对象,
2,延迟加载, 由于要保证线程安全,使用了synchronized来保证创建过程的线程同步
3,使用内部类
/** * 本示例主要演示了三种单例模式的实现方式,并对各种实现方式的优缺点进行比较。 * 1,静态变量直接创建单例对象, * 2,延迟加载, 由于要保证线程安全,使用了synchronized来保证创建过程的线程同步 * 3,使用内部类 */ package Pattern; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 单例模式 * @author LPX * */ public class StaticSingleton { private StaticSingleton(){ System.out.println("StaticSingleton creating."); } /** * * @author LPX * */ private static class SingletonHolder{ static{ System.out.println("SingletonHolder static statements."); } //Holder在该类中只会创建一次,并且默认对多线程是友好的。 public static StaticSingleton Holder=new StaticSingleton(); } public static StaticSingleton getInstance(){ return StaticSingleton.SingletonHolder.Holder; } //在类进行加载时,就会进行创建,比如,在使用StaticSingleton.other()方法时,就会进行加载。 private static StaticSingleton instance=new StaticSingleton(); public static StaticSingleton getInstance3(){ return instance; } private static StaticSingleton lazyInstance=null; /** * 需要使用同步机制synchronized来保证对lazyInstance的判断与赋值是线程安全 * 在该方法中由于要进行数据同步,所以在多线程的环境中性能会有较低 * @return */ public static synchronized StaticSingleton getInstance2(){ if(lazyInstance==null){ lazyInstance=new StaticSingleton(); } return lazyInstance; } public static void other(){ System.out.println("Other"); } public static void main(String[] args){ final long start=System.currentTimeMillis(); Runnable runable=new Runnable(){ @Override public void run() { long start=System.currentTimeMillis(); //long start=System.currentTimeMillis(); for(int i=0;i<100000;i++){ StaticSingleton.getInstance2(); } System.out.println("多线程用时:"+(System.currentTimeMillis()-start)); } }; /* ExecutorService exe=Executors.newFixedThreadPool(1); exe.submit(new Thread(runable)); exe.submit(new Thread(runable)); exe.submit(new Thread(runable)); exe.submit(new Thread(runable)); exe.submit(new Thread(runable)); exe.submit(new Thread(runable));*/ StaticSingleton.other(); for(int i=0;i<100000;i++){ StaticSingleton.getInstance3(); } System.out.println("用时:"+(System.currentTimeMillis()-start)); } }
View Code
相关文章推荐
- 【计算机网络】关于三种网络通信模式以及java中三种通信方式的实现介绍
- 设计模式之单例模式(三种实现方式)
- 日常小结-多线程的单例模式的三种实现方式
- 单例模式(Singleton pattern)的三种写法(含枚举实现方式)
- 设计模式之单例模式(三种实现方式)
- Java 实现工厂设计模式的三种方式
- 消费者模式的三种实现方式
- Python中实现装饰模式的三种方式
- 三种方式实现生产者和消费者模式
- Swift 实现单例模式Singleton pattern的三种方法
- ApplicationContext的三种实现方式以及在web.xml配置的两种方式
- 单例模式的两种实现方式及区别
- JAVA多线程的三种实现方式
- sso单点登录的三种实现方式
- Android中Video的三种播放方式的实现
- Squid三种代理方式的实现及ACL
- ReentrantLock方式实现生产者-消费者模式
- Android HAL实现的三种方式(2) - 基于Service的HAL设计
- JAVA多线程实现的三种方式
- 单例设计模式实现方式