You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java单例模式下私有变量仅自增一次的原理咨询

解答:单例模式中构造器仅执行一次的Java原理

Hey there! Let's break down exactly why your a variable only increments once even though you're triggering instance retrieval three times. It all boils down to how Java Singleton Pattern works and the core rules of class vs instance-level members.

核心逻辑:单例的"唯一实例"保证

First off, the entire purpose of a singleton is to ensure only one instance of the class exists throughout your application. Here's how your code enforces that:

  • The constructor private ClassicSingleton() is marked private—this means no external code can directly call new ClassicSingleton() to create a new object.
  • The static variable private static ClassicSingleton instance = null belongs to the ClassicSingleton class itself (not any specific object instance). Once this variable is assigned an instance, it stays that way for the class's lifetime.

执行流程一步步拆解

Let's walk through what happens each time you call the singleton's getInstance() method (I'm assuming it's the standard lazy-loaded implementation):

  1. First call: instance is null, so the code creates a new instance via new ClassicSingleton(). This triggers the private constructor, where a++ runs (turning a from 0 to 1) and your print statements execute.
  2. Second & third calls: instance is already pointing to the existing object. The code skips creating a new instance and just returns the one that was already made. The constructor never gets called again—so a++ never runs those extra times.

额外澄清:实例变量 vs 静态变量

Just to clear up the difference between your a and b variables:

  • private int a = 0 is an instance variable: Each new object gets its own copy. But since we only ever create one singleton instance, a is initialized once and modified once.
  • static int b = 0 is a class variable: There's only one copy shared across all instances (even if no instances exist). If you had put b++ in the constructor, it would also only run once here—same reason, constructor only executes once.

快速验证方法

If you add a print statement in your getInstance() method that outputs the instance's hash code, you'll see all three calls return the exact same object. That's the singleton guarantee in action!

内容的提问来源于stack exchange,提问作者Kad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:15:47