/**
* 描述:
* 懒汉模式
*
* @author 小纸人
* @create 2019-03-10 22:01
*/
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {
}
public static LazySingleton getInstance(){
if (instance == null){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new LazySingleton();
}
return instance;
}
}
class MainLazySingleton{
public static void main(String[] args){
LazySingleton instance1 = LazySingleton.getInstance();
LazySingleton instance2 = LazySingleton.getInstance();
System.out.println(instance1 == instance2);
//多线程测试
// TestLazySingleton thread1= new TestLazySingleton();
// TestLazySingleton thread2= new TestLazySingleton();
// thread1.start();
// thread2.start();
}
}
class TestLazySingleton extends Thread{
@Override
public void run() {
System.out.println(LazySingleton.getInstance());
}
}
单例懒汉模式
最新推荐文章于 2023-03-10 15:41:36 发布