主程序入口
class Program
{
static void Main(string[] args)
{
MawbMethod M = MawbMethod.getMawbObj();
M.Print();
//Thread thread = new Thread(fun);
//thread.Start();
//thread.IsBackground = true;
//测试多线程情况下不加lock
//TaskFactory taskFactory = new TaskFactory();
//List<Task> taskList = new List<Task>();
//for (int i = 0; i < 6; i++)
//{
// taskList.Add(taskFactory.StartNew(() =>
// {
// MawbMethod M = MawbMethod.getMawbObj();
// }));
//}
//taskFactory.ContinueWhenAny(taskList.ToArray(), t => {
// Console.WriteLine("有一个任务执行完成");
//});
//taskFactory.ContinueWhenAny(taskList.ToArray(), t => {
// Console.WriteLine("所有任务执行完成");
//});
Console.Read();
}
//private static void fun()
//{
// MawbMethod M = MawbMethod.getMawbObj();
// M.Print();
//}
}
实例化类
public class MawbMethod
{
private static volatile MawbMethod mawbAttribute;
private static readonly object locker = new object();
//构造函数必须是私有的
//这样在外部便无法使用 new 来创建该类的实例
private MawbMethod()
{
}
/// <summary>
/// 定义一个全局访问点
/// 设置为静态方法
/// 则在类的外部便无需实例化就可以调用该方法
/// </summary>
/// <returns></returns>
public static MawbMethod getMawbObj()
{
//为什么加两次等于空判断,比如5个线程同时进入lock中,其中第一个线程正在执行,其余4个线程等待,当第1个线程解锁后,
//公共变量已经赋值,如果不加判断会出现重复申明。
if (mawbAttribute == null)
{
lock (locker)
{
if (mawbAttribute == null)
{
Console.WriteLine("对象: " + mawbAttribute);
Console.WriteLine("线程时间: "+DateTime.Now);
mawbAttribute = new MawbMethod();
}
}
}
return mawbAttribute;
}
public void Print()
{
Console.WriteLine("成功!");
}
}