Skip to content

Instantly share code, notes, and snippets.

@diaolizhi
Created November 13, 2018 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diaolizhi/d99123768f71c13bc8b3f95d2be61bd6 to your computer and use it in GitHub Desktop.
Save diaolizhi/d99123768f71c13bc8b3f95d2be61bd6 to your computer and use it in GitHub Desktop.
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