public class MyBenchmark {
public static void main(String[] args) {
new Thread(()-> {
Singleton instance1 = Singleton.getInstance();
},"t1").start();
new Thread(()-> {
Singleton instance2 = Singleton.getInstance();
},"t2").start();
}
}
@Slf4j(topic = "c.Singleton")
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
log.debug("已创建"); //若是单线程,则永远只会输出1次。多线程,则可能会输出多次
}
return instance;
}
}