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

首頁 > 編程 > .NET > 正文

.NET 線程同步(2)

2024-07-10 13:00:19
字體:
來源:轉載
供稿:網友
monitor類的tryenter()方法非常類似于enter()方法,他試圖獲得對象的獨占鎖,不過它不會象enter()方法那樣暫停. 如果線程成功進入,則tryenter()方法返回true.
tryenter()有3種重載方法,其中兩個都帶有超時參數,表示等待鎖定的時間.

using system;
using system.threading;

namespace monitortryenter
{
public class tryenter
{
public tryenter()
{
}

public void criticalsection()
{
bool b=monitor.tryenter(this,1000);
console.writeline("thread "+thread.currentthread.gethashcode()+" tryenter value "+b);
for(int i=1;i<=3;i++)
{
thread.sleep(1000);
console.writeline(i+" "+thread.currentthread.gethashcode()+" ");
}
monitor.exit(this);
}

public static void main()
{
tryenter a=new tryenter();
thread t1=new thread(new threadstart(a.criticalsection));
thread t2=new thread(new threadstart(a.criticalsection));
t1.start();
t2.start();
}
}
}
運行結果:



在可能發生競爭,但不希望線程睡眠某個未指定的時間時,就可以使用tryenter().

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乌审旗| 荆门市| 弥渡县| 额济纳旗| 南华县| 新晃| 远安县| 衡南县| 商洛市| 本溪市| 峡江县| 乌拉特中旗| 高安市| 双鸭山市| 大悟县| 乐平市| 黄山市| 黑龙江省| 阜平县| 佛山市| 柯坪县| 黔东| 宁化县| 阳信县| 乌拉特中旗| 秦安县| 额敏县| 远安县| 时尚| 彝良县| 巨野县| 罗山县| 虞城县| 正宁县| 沂南县| 吉安市| 安丘市| 筠连县| 河源市| 江北区| 开阳县|