gpt4 book ai didi

java - Java单例类有漏洞吗?

转载 作者:行者123 更新时间:2023-12-02 06:33:33 25 4
gpt4 key购买 nike

java中的单例类是指一个只能被初始化一次的类,并且所有类都将使用同一个对象。只会为每个人创建一个对象。但我的问题是,当多个线程同时初始化同一个对象时,会发生什么?会有两个或更多物体吗?我们如何限制这一点?

最佳答案

But my question is when more than one threads will be there to initialize the same object at the same time what will be happened there? Will there be two or more objects? How can we restrict this?

实现它的多种方法:

  1. 同步可用于控制多线程环境中单例类的多个对象的创建。

  2. 在类加载期间使用静态 block 创建单例对象。

Wiki 描述了在考虑多线程环境的情况下以出色的方式编写 Singleton 类的方法。

http://en.wikipedia.org/wiki/Singleton_pattern

关于java - Java单例类有漏洞吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19874432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com