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

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

(一).描述

此示例演示分别用lock以及Interlicked和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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航