1.单例模式
1.简单的单例模式
package Slogan;
public class LazySingletonTest {
public static void main(String[] args) {
LazySingleton instance1 = LazySingleton.getInstance();
System.out.println("instance1 = " + instance1);
LazySingleton instance = LazySingleton.getInstance();
System.out.println("instance2 = " + instance2);
}
}
class LazySingleton {
private static LazySingleton lazySingleton = null;
LazySingleton() {
}
public static LazySingleton getInstance() {
if (lazySingleton == null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
此时屏幕打印出的两个对象是一致的,但是在多线程的情况下,会产生一些问题
2.多线程下的单例模式
package Slogan;
public class LazySingletonTest {
public static void main(String[] args) {
new Thread(() -> {
LazySingleton instance = LazySingleton.getInstance();
System.out.println("instance = " + instance);
}).start();
new Thread(() -> {
LazySingleton instance = LazySingleton.getInstance();
System.out.println("instance = " + instance);
}).start();
}
}
class LazySingleton {
private static LazySingleton lazySingleton = null;
LazySingleton() {
}
public synchronized static LazySingleton getInstance() {
if (lazySingleton == null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
需要在方法的前面加锁,也就是synchronized
但是仍是有优化空间
3.优化多线程单例模式
package Slogan;
public class LazySingletonTest {
public static void main(String[] args) {
new Thread(() -> {
LazySingleton instance = LazySingleton.getInstance();
System.out.println("instance = " + instance);
}).start();
new Thread(() -> {
LazySingleton instance = LazySingleton.getInstance();
System.out.println("instance = " + instance);
}).start();
}
}
class LazySingleton {
private static LazySingleton lazySingleton = null;
LazySingleton() {
}
public static LazySingleton getInstance() {
if (lazySingleton == null) {
//第一次进行加锁
synchronized (LazySingleton.class) {
//为了防止并发情况下多次new对象
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
}
}
return lazySingleton;
}
}
[...]Docker容器 -2021Dubbo框架 -2020Git版本控制-20180Golang语言入门-2021Java设计模式-2019JVM探究-2019Mybatis框架-2019MySQL数据库-2019Netty网络编程框架-2021Redis数据库-2020SMS框架整合-2019Spring框架-2018Springboot框架-2019Springmvc框架-2019SVN版本控制-[...]