public class Manager {
private static Manager _one;
private static Manager _two;
private static object Obj_Lock_one = new object();
private static object Obj_Lock_two = new object();//Do I need Obj_Lock_two here ?
public static Manager GetOne ()
{
if (_one == null)
{
lock (Obj_Lock_one)
{
if (_one == null)
{
_one = new Manager();
}
}
}
return _one;
}
public static Manager GetTwo ()
{
if (_two == null)
{
lock (Obj_Lock_two) //Do I need Obj_Lock_two here ?
{
if (_two == null)
{
_two = new Manager();
}
}
}
return _two;
}
}
我需要第二个obj来锁定吗?在GetTwo方法中,我应该使用“lock(Obj_Lock_one)”或“lock(Obj_Lock_two)”
如果我只使用一个obj锁定,可能会阻止一个,我认为...
那么正确的方法是什么?
答案 0 :(得分:1)
我需要第二个obj来锁定吗?
如果两个线程同时第一次同时调用GetOne()
和GetTwo()
,则使用第二个锁定对象将稍微提高性能。换句话说:你可能无法衡量差异。
那么正确的方法是什么?
不要重新发明轮子。废弃您的代码并使用Lazy initialization with Lazy<T>
代替,这是线程安全的并自动处理所有这些线程同步问题:
public sealed class Manager
{
private static readonly Lazy<Manager> lazyOne = new Lazy<Manager>(() => new Manager());
private static readonly Lazy<Manager> lazyTwo = new Lazy<Manager>(() => new Manager());
public static Manager GetOne() { return lazyOne.Value; }
public static Manager GetTwo() { return lazyTwo.Value; }
}