单例模式面试题

设计模式 - 单例模式 1. 在Java中实现单例模式有哪些方法 单例模式是指一个类在任何情况下只有一个实例,并且提供全局访问点来获取该实例。 要实现单例模式,需满足 私有化构造方法,防止被外部实例化造成多实例问题; 提供一个静态方法作为全局访问点来获取唯一的实例对象。 实现单例的方法: 延迟加载 通过延迟加载的方式进行实例化,并增加了同步锁机制,避免多线程下的线程安全问题。 public class Singleton { private static Singleton instance; // 私有化构造函数,防止外部实例化 private Singleton() { // 初始化代码 } // 提供一个公共的静态方法来获取实例 public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } 缺点:有性能问题,同步锁只在第一次实例化时有用,后续不需要。 双重检查锁 双检锁来缩小锁的范围以提升性能 public class Singleton { private static volatile Singleton instance; // 私有化构造函数,防止外部实例化 private Singleton() { // 初始化代码 } // 提供一个公共的静态方法来获取实例 public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } 饿汉式 在类加载时就触发了实例化,从而避免多线程同步问题。 ...

七月 15, 2025 · 2 分钟 · 314 字

Interview Threads Pool

java八股文 - 多线程与线程池

七月 14, 2025

Java面试八股文之锁

java八股文 - J.U.C和锁

七月 13, 2025

How to Use Mybatis Generator

Introduction to using MyBatis Generator.

七月 1, 2025