首页 > 编程 > .NET > 正文

.NET线程同步(1)

2024-07-10 13:00:19
字体:
来源:转载
供稿:网友
在处理.net线程同步问题,有许多办法,这里所将谈到的是特定代码区的同步.

这些特定的代码区是方法中重要的代码段,他们可以改变对象的状态,或者更新另一个资源.

monitor类用于同步代码去,其方式是使用monitor.enter()方法获得一个锁,然后使用monitor.exit()方法释放该锁.

示例如下:

using system;
using system.threading;

namespace enterexit
{
public class enterexit
{
private int result=0;
public enterexit()
{
}

public void noncriticalsection()
{
console.writeline("enter threah"+thread.currentthread.gethashcode());
for(int i=1;i<=5;i++)
{
console.writeline("result="+result++ +" threadid"+thread.currentthread.gethashcode());
thread.sleep(1000);
}
console.writeline("exiting threah"+thread.currentthread.gethashcode());
}

public void criticalsection()
{
monitor.enter(this);
console.writeline("enter threah"+thread.currentthread.gethashcode());
for(int i=1;i<=5;i++)
{
console.writeline("result="+result++ +" threadid"+thread.currentthread.gethashcode());
thread.sleep(1000);
}
console.writeline("exiting threah"+thread.currentthread.gethashcode());
monitor.exit(this);
}

public static void main(string[] args)
{

enterexit e=new enterexit();
if(args.length>0)
{
thread nt1=new thread(new threadstart(e.noncriticalsection));
nt1.start();

thread nt2=new thread(new threadstart(e.noncriticalsection));
nt2.start();
}
else
{
thread ct1=new thread(new threadstart(e.criticalsection));
ct1.start();

thread ct2=new thread(new threadstart(e.criticalsection));
ct2.start();
}
}
}

}



运行结果:

enter threah 1

result=0 thread1

result=1 thread1

result=2 thread1

result=3 thread1

result=4 thread1

exiting thread1

enter threah 2

result=5 thread2

result=6 thread2

result=7 thread2

result=8 thread2

result=9 thread2

exiting thread2

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表