一、准备条件
1. 代码
package com.zhang.pattern.singleton;
/**
* 单例模式:饿汉-不考虑线程安全
*/
public class LazySimpleSingleton {
private LazySimpleSingleton() {
}
private static LazySimpleSingleton instance;
public static LazySimpleSingleton getInstance() {
if (instance == null) {
instance = new LazySimpleSingleton();
}
return instance;
}
}
2. 测试代码
package com.zhang.pattern;
import com.zhang.pattern.singleton.LazySimpleSingleton;
import org.junit.Test;
public class LazySimpleSingletonTest {
@Test
public void testLazySimpleSingleton() {
Thread thread1 = new Thread(() -> System.out.println(Thread.currentThread().getName() + ": " + LazySimpleSingleton.getInstance()));
Thread thread2 = new Thread(() -> System.out.println(Thread.currentThread().getName() + ": " + LazySimpleSingleton.getInstance()));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("caught InterruptedException, ignore it");
}
}
}
二、Debug调试
1. 打断点,将断点设置为Tread模式
右键单击断点,即可设置,勾选Thread。
2. 开始调试
点击Debug开始调试:
程序在断点处停下来了,我们选择Thread-0,然后进入if语句内部:
然后切换到Thread-1,直接运行结束:
然后切换到Thread-0,也运行结束,就得到了以下结果:
好,以上就是IDEA在多线程环境下,测试懒汉式单例模式线程安全的示范,供大家参考,欢迎留言评论!