private static LocalBroadcastManager mInstance; @NonNull public static LocalBroadcastManager getInstance(@NonNull Context context) { synchronized (mLck) { if (mInstance == null) { mInstance = new LocalBroadcastManager(context.getApplicationContext()); } return mInstance; } }
系统下的这种单例 是安全的吗 感觉很乖
![]() | 1 monkeylmj 2021-11-23 16:55:27 +08:00 安全,就是效率低, 每次拿都要加锁。 |
2 rcj6056 OP 但是他这个 mInstance 没用 volatile 修饰 在 new 对象的时候会不会有可能导致重排 mInstance 为 null 的情况 |
![]() | 3 xFrye 2021-11-23 19:41:23 +08:00 @rcj6056 先弄清楚,这个 synchronized 关键字锁的到底是什么。然后对比下你在网上看到的 dcl 单例,看看写法有什么不同? |
4 DCELL 2021-11-23 20:18:17 +08:00 我记得是这样的哇: if null lock{ if null new() } return install |