国产探花免费观看_亚洲丰满少妇自慰呻吟_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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 马山县| 鄄城县| 济宁市| 郓城县| 九江市| 武平县| 吉隆县| 宿松县| 西城区| 南安市| 县级市| 双城市| 泗阳县| 壶关县| 津南区| 绍兴县| 偃师市| 页游| 江门市| 顺昌县| 金坛市| 慈利县| 伊春市| 怀安县| 汉寿县| 温宿县| 临高县| 乌鲁木齐县| 滁州市| 焉耆| 镇平县| 西充县| 吴旗县| 新河县| 昌黎县| 沅江市| 洪洞县| 淅川县| 治县。| 宁明县| 宜兰县|