您的位置:首页 > 其它

三种单例模式的实现方式

2014-04-22 15:47 148 查看
本示例主要演示了三种单例模式的实现方式,并对各种实现方式的优缺点进行比较。
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: