说明:参考《Java多线程核心技术》
4、单例模式
1、双检测机制的延迟加载单例模式
public class DCLSingleton {
private volatile static ThreadA threadA;
public DCLSingleton() {
}
// 使用双检测机制来解决问题,既保证不需要同步代码的异步执行,又保证了单例的特性
public static ThreadA getInstance() {
try {
if (threadA != null) {
} else {
Thread.sleep(1000);
synchronized (ThreadA.class){
if (threadA == null) {
threadA = new ThreadA();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return threadA;
}
}
public class DCLSingletonTest {
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
ThreadA threadA1 = new ThreadA();
ThreadA threadA2 = new ThreadA();
threadA.start();
threadA1.start();
threadA2.start();
}
}
/**
33689776
33689776
33689776
*/
2、静态内部类的延迟加载
public class StaticSingleton {
// 内部类方式
private static class MyObjectHandler {
private static StaticSingleton singleton = new StaticSingleton();
}
public StaticSingleton() {
}
public static StaticSingleton getInstance() {
return MyObjectHandler.singleton;
}
}
public class ThreadA extends Thread{
@Override
public void run() {
System.out.println(StaticSingleton.getInstance().hashCode());
}
}
public class StaticSingletonTest {
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
ThreadA threadA1 = new ThreadA();
ThreadA threadA2 = new ThreadA();
threadA.start();
threadA1.start();
threadA2.start();
}
}
/**
797782832
797782832
797782832
*/
3、静态代码块的延迟加载模式
public class StaticBlockSingleton {
private static StaticBlockSingleton instance = null;
public StaticBlockSingleton() {
}
static {
instance = new StaticBlockSingleton();
}
public static StaticBlockSingleton getInstance() {
return instance;
}
}
public class ThreadA extends Thread{
int num = 3;
@Override
public void run() {
for (int i = 0; i < num ; i++) {
System.out.println(StaticBlockSingleton.getInstance().hashCode());
}
}
}
public class StaticBlockSingletonTest {
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
ThreadA threadA1 = new ThreadA();
ThreadA threadA2 = new ThreadA();
threadA.start();
threadA1.start();
threadA2.start();
}
}
/**
256150948
256150948
256150948
256150948
256150948
256150948
256150948
256150948
256150948
*/