Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
线程只有在条件uniqueInstance == null设置为真时才会进入同步代码,那有什么必要在临界区内再次检查呢?
uniqueInstance == null
因为在检查和同步调用之间,您可能会被另一个获取信号量、写入单例并退出的进程中断。除非您再次检查,否则您可能会覆盖其他进程已经初始化的值。
另一方面,如果您使整个方法同步,您将在每次调用单例时支付同步成本,而不仅仅是第一次调用。最好检查两次。