正文

线程--分别用lock以及Interlocked和Monitor类实现线程的临界2006-05-26 11:41:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/Csharpsky/14896.html

分享到:

(一).描述   此示例演示分别用lock以及Interlocked和Monitor类实现线程的临界区操作(互斥)(二).代码   using System;using System.Threading;using System.Collections; namespace 加锁_实现临界区互斥操作_{  //委托声明(函数签名) delegate string MyMethodDelegate();  class MyClass {    private static ArrayList arrList = new ArrayList();   private static int i = 0;    public static void Add()     {   //方法一:用 lock 实现//   lock(arrList)//   {//    arrList.Add(i.ToString());//    i++;//   }      //方法二: 用Interlicked类实现//   System.Threading.Interlocked.Increment(ref i);//   arrList.Add(i.ToString());    //方法三: 用Monitor类实现   try   {    //I.不限时间    //stem.Threading.Monitor.Enter(arrList);          //II.在指定时间获得排他锁    if(System.Threading.Monitor.TryEnter(arrList,TimeSpan.FromSeconds(30))) //在30秒内获取对象排他锁. 灵活运用可以实现防止死锁功能    {                                                                       //避免互相等待情况。 在一定时间内得不到排他锁,可能是自己                                                                         //占用其它排它锁造成的(别的正在等自己正占用的排它锁,而处于等待状态),                                                                         //这时可以释放掉自己正占用的排他锁后,再试图去得到想要的对象的排他锁     arrList.Add(i.ToString());                                             i++;    }   }   catch   {    //发生异常后自定义错误处理代码   }   finally   {    Monitor.Exit(arrList);  //不管是正常还是发生错误,都得释放对象   }  }     [STAThread]  static void Main(string[] args)  {   Thread thread1 = new Thread(new ThreadStart(Add));   Thread thread2 = new Thread(new ThreadStart(Add));     Thread thread3 = new Thread(new ThreadStart(Add));    thread1.Start();   thread2.Start();   thread3.Start();    Console.Read();    for(int i=0;i<arrList.Count;i++)   {    Console.WriteLine(arrList[i].ToString());   }    Console.Read();   } }} 本示例代码已经测试,能够正常运行! (三).示例下载  http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar  

阅读(3532) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册