单例模式
- 饿汉模式
private static HungrySingleton instance = new HungrySingleton();
public static HungrySingleton getInstance() {
return instance;
}
类加载时直接创建单例对象,天生线程安全。
懒汉模式
public class LazySingleton {
private static LazySingleton instance;
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
非线程安全,测试如下:
public class Person implements Runnable {
private CountDownLatch latch;
public Person(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
HungrySingleton hungrySingleton = HungrySingleton.getInstance();
hungrySingleton.output();
latch.countDown();
}
}
public class SingletonTest {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(10);
long start = System.currentTimeMillis();
System.out.println("starting...");
for (int i = 0; i < 10; i++) {
Person p = new Person(countDownLatch);
Thread thread = new Thread(p);
thread.start();
}
try {
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
long now = System.currentTimeMillis();
System.out.println("cost: "+ (now-start)+" ms");
}
}
结果如图:
starting...
LazySingleton@41672b2d
LazySingleton@64a0b27
LazySingleton@78814553
LazySingleton@620196ec
LazySingleton@994e424
LazySingleton@72460481
LazySingleton@65afe199
LazySingleton@4c630b0d
LazySingleton@32c3e0c4
LazySingleton@3ceef829
cost: 13 ms
- 常用单例
1) getInstance方法加同步
public class SyncLazySingleton {
private static SyncLazySingleton instance;
public static synchronized SyncLazySingleton getInstance() {
if (instance == null) {
instance = new SyncLazySingleton();
}
return instance;
}
}
2)Double-Check
public class DoubleCheckLazySingleton {
private static volatile DoubleCheckLazySingleton instance;
public static DoubleCheckLazySingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckLazySingleton.class) {
if (instance == null) {
instance = new DoubleCheckLazySingleton();
}
}
}
return instance;
}
}
3)内部类(嵌套内部类,非普通内部类)
public class InnerClassSingleton {
private static class LazyHolder {
private static final InnerClassSingleton instance = new InnerClassSingleton();
}
public static InnerClassSingleton getInstance(){
return LazyHolder.instance;
}
}
待续。。。