💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 高并发下线程安全的单例模式 #### Double Check Locking 双检查锁机制 ``` public class MySingleton { //使用volatile关键字保其可见性 volatile private static MySingleton instance = null; private MySingleton(){} public static MySingleton getInstance() { try { if(instance != null){//懒汉式 }else{ //创建实例之前可能会有一些准备性的耗时工作 Thread.sleep(300); synchronized (MySingleton.class) { if(instance == null){//二次检查 instance = new MySingleton(); } } } } catch (InterruptedException e) { e.printStackTrace(); } return instance; } } ``` #### 使用静态内置类实现单例模式 ``` public class MySingleton { //内部类 private static class MySingletonHandler{ private static MySingleton instance = new MySingleton(); } private MySingleton(){} public static MySingleton getInstance() { return MySingletonHandler.instance; } } ``` #### 使用static代码块实现单例 ``` public class MySingleton{ private static MySingleton instance = null; private MySingleton(){} static{ instance = new MySingleton(); } public static MySingleton getInstance() { return instance; } } ``` 更多方法:[https://blog.csdn.net/cselmu9/article/details/51366946](https://blog.csdn.net/cselmu9/article/details/51366946/)