/**
* 单例模式。
* @author Bright Lee
*/
public class LazySingleton {
private static volatile LazySingleton instance;
private LazySingleton() {
System.out.println("构造方法被调用了,当前时间戳是:" +
System.currentTimeMillis());
}
public static LazySingleton getInstance() {
if (instance == null) {
synchronized(LazySingleton.class) {
if (instance == null) {
instance = new LazySingleton();
}
}
}
return instance;
}
public static void main(String[] args) {
// 并发调用100遍,构造方法只会被调用一次:
for (int i = 0; i < 100; i++) {
new Thread() {
public void run() {
LazySingleton.getInstance();
}
}.start();
}
}
}
设计模式:单例模式(懒汉)
猜你喜欢
转载自blog.csdn.net/look4liming/article/details/84633658
今日推荐
周排行