标签:内部类 length get roi main start pre str ring
代码如下:
public class SingletonB {
private static volatile SingletonB mInstance;
private SingletonB() {
System.out.println("双重检验锁方法单例模式");
}
public static SingletonB getInstance() {
if (mInstance == null) {
synchronized (SingletonB.class) {
if (mInstance == null) {
mInstance = new SingletonB();
}
}
}
return mInstance;
}
}
代码如下:
public class SingletonA {
private SingletonA() {
System.out.println("内部类方法单例模式");
}
private static class Singleton {
private static final SingletonA INSTANCE = new SingletonA();
}
public static SingletonA getInstance() {
return Singleton.INSTANCE;
}
}
测试代码:
public class Test {
public static void main(String[] args) {
Thread[] threads = new Thread[10000];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread() {
public void run() {
SingletonA.getInstance();
SingletonB.getInstance();
};
};
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
}
}
运行了N次,两个单例模式都是只运行了一次构造函数。
标签:内部类 length get roi main start pre str ring
原文地址:https://www.cnblogs.com/shenchanghui/p/9114283.html