单例模式
- 最近刷面试题碰到一个问题,单例模式懒汉式多线程下是否安全?
1.例子
/**
* 懒汉式,线程不安全问题
*/
public class LazyTest {
private static LazyTest lazyTest = null;
public static LazyTest getLazyTest(){
if(lazyTest == null){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lazyTest = new LazyTest();
}
return lazyTest;
}
public static void main(String[] args) {
IntStream.range(0,10).forEach((e) -> new Thread(() -> System.out.println(LazyTest.getLazyTest() == LazyTest.getLazyTest())).start());
}
}
结果:显然是线程不安全的
2.改成线程安全
(1)可以用synchronized关键字修饰
(2)用lock锁,或者其它的锁