using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication11
{
public class Singleton3
{
private static Singleton3 _Instance;
private static object _TheLock;
private Singleton3()
{ }
public static Singleton3 Instance
{
get
{
if (_Instance == null)
{
lock (_TheLock) //问题1、这里的_TheLock是空对象(null),那么锁定“空对象”有什么作用?锁定空对象能起到锁的作用么?
{
if (_Instance == null) //问题2、为什么这里又要进行判断?
{
_Instance = new Singleton3();
}
}
}
return Singleton3._Instance;
}
set
{
Singleton3._Instance = value;
}
}
}
}
问题2是防止多线程情况下产生两个实例3:好像不需要set属性吧
if (_Instance == null)
{
------------------------------------------1
lock (_TheLock)
{
------------------------------------------2
_Instance = new Singleton3();
}
------------------------------------------3
}没有第二个判断的可能情况:假设两个线程A和B
都到达lock(1处)
A进入lock执行(2处) 此时B等待(仍在1处)
当A执行完毕lock的代码后(到达3) 新实例化了一个对象并返回
B开始进入lock执行(2处) 又会实例化出一个对象 此对象并不是之前A创建的那个对象了 何谈"单体"呢?
我为什么觉得lock外面的那个判断多余呢? 谁讲下啊
class SingleTest
{
//私有的唯一静态成员,类加载就创建好的单例对象
private static readonly SingleTest test = new SingleTest(); private SingleTest() { } //静态方法返回唯一的实例
public static SingleTest GetSingle()
{
return test;
}}
楼主的程序可以指定实例化的时机(即在第一次调用GetSingle方法的时候进行实例化) 而这个不管用到用不到 都会实例化一个"等着"