困惑(线程锁)

来源:互联网 发布:如何投资 知乎 编辑:程序博客网 时间:2024/06/04 18:41

写两种常用的单例模式实现,对比一下两种方式的实现有什么差异:

No1:

public class Test {private static Test instance = null;public static Test getInstance(){synchronized (Test.class) {        if (instance == null) {        instance = new Test();   }}return instance;}}

No2:

public class Test {private static Test instance = null;public synchronized static Test getInstance(){if (instance == null) {instance = new Test();}return instance;}}


原创粉丝点击