(六)线程--分别用lock以及Interlocked和Monitor类实现线程的临界区操作(互斥)(示例下载)

(一).描述
   此示例演示分别用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
  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值