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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 利川市| 敦化市| 神木县| 崇州市| 津南区| 惠来县| 东乡| 东安县| 广宗县| 讷河市| 长汀县| 庆云县| 溧水县| 江川县| 普安县| 韶关市| 泰安市| 北安市| 墨江| 松滋市| 正镶白旗| 贵阳市| 阿荣旗| 嘉禾县| 太谷县| 延津县| 鄯善县| 页游| 陇西县| 元氏县| 曲沃县| 荔波县| 泽库县| 江津市| 海林市| 萨嘎县| 莆田市| 女性| 江孜县| 晋州市| 九龙县|