国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 昌邑市| 长寿区| 攀枝花市| 天等县| 民勤县| 屯门区| 启东市| 楚雄市| 山阴县| 邹城市| 云林县| 绍兴县| 雷山县| 白朗县| 晋江市| 湖口县| 讷河市| 沙雅县| 玛纳斯县| 治县。| 盐池县| 广昌县| 香港| 旺苍县| 张家口市| 翼城县| 观塘区| 潼关县| 连南| 临沭县| 福鼎市| 顺平县| 哈密市| 渑池县| 上高县| 神木县| 阳城县| 故城县| 金塔县| 依安县| 昌吉市|