Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java 懒汉式单例模式 - 线程安全
package chapter3;
/**
* @program: studythread2
* @description: 懒汉式单例模式
* @author: diaolizhi
* @create: 2018-11-13 12:39
**/
public class LazySingleton {
private static volatile LazySingleton lazySingleton = null;
/**
* @Description: 不加任何限制,只是模拟创建对象耗时
* @Param: []
* @return: chapter3.LazySingleton
* @Author: diaolizhi
* @Date: 2018/11/13
*/
public static LazySingleton getInstance() {
if(lazySingleton == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
public static synchronized LazySingleton getInstance1() {
if(lazySingleton == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
public static LazySingleton getInstance2() {
if(lazySingleton == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 为了防止指令重排序,在静态变量 lazySingleton 加关键字:volatile
synchronized (LazySingleton.class) {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
}
}
return lazySingleton;
}
private LazySingleton() {
}
}
package chapter3_test;
import chapter3.LazySingleton;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* @program: studythread2
* @description: 懒汉式单例模式测试
* @author: diaolizhi
* @create: 2018-11-13 12:44
**/
public class LazySingletonTest {
@Test
@DisplayName("懒汉式单例模式:测试不加其他操作(模拟创建对象耗时)")
void test() {
for(int i=0; i<10; i++) {
new Thread(() -> {
LazySingleton instance = LazySingleton.getInstance();
System.out.println(instance);
}).start();
}
while (true);
}
@Test
@DisplayName("懒汉式单例模式:整个 getInstance 加 synchronized")
void test1() {
for(int i=0; i<10; i++) {
new Thread(() -> {
LazySingleton instance = LazySingleton.getInstance1();
System.out.println(instance);
}).start();
}
while (true);
}
@Test
@DisplayName("懒汉式单例模式:代码块加 synchronized,并使用 volatile")
void test2() {
for(int i=0; i<10; i++) {
new Thread(() -> {
LazySingleton instance = LazySingleton.getInstance2();
System.out.println(instance);
}).start();
}
while (true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.