饿汉式--本身线程安全
在类加载的时候,已经进行实例化
/**
* 饿汉式单例
* 类加载的时候就实例化
*/
public class HungerSingleton {
private static HungerSingleton ourInstant = new HungerSingleton();
public static HungerSingleton getInstance(){
return ourInstant;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(getInstance().toString());
}).start();
}
}
}
懒汉式--非线程安全
package threadTest;
/**
* 懒汉式实例
* 在需要的时候再实例化
*/
public class LazySingleton {
private static LazySingleton lazyInstance = null;
private static LazySingleton getInstance(){
// 判断实力是否为空
if(null==lazyInstance){
try {
Thread.sleep(1000l);
}catch (InterruptedException e){
e.printStackTrace();
}
lazyInstance = new LazySingleton();
}
return lazyInstance;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(getInstance().toString());
}).start();
}
}
}
改成线程安全 双重判定
/**
* 懒汉式实例
* 在需要的时候再实例化
*/
public class LazySingleton {
private static LazySingleton lazyInstance = null;
private static LazySingleton getInstance(){
// 判断实力是否为空
if(null==lazyInstance){
try {
Thread.sleep(1000l);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (LazySingleton.class){
if(null==lazyInstance){
lazyInstance = new LazySingleton();
}
}
}
return lazyInstance;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(getInstance().toString());
}).start();
}
}
}