我有兩種方法,第一()和第二(),我將它們分配給兩個線程。與Monitor.Pulse線程同步NOT按預期工作
以下是我的第二和第一方法
public void first()
{
lock (this)
{
Monitor.Wait(this);
Console.WriteLine("First");
Monitor.Pulse(this);
}
}
public void second()
{
lock (this)
{
//Monitor.Wait(this);
Console.WriteLine("Second");
Monitor.Pulse(this);
}
}
的問題是在控制檯上只有「二」是越來越打印。 儘管我在第二個()中有Monitor.Pulse()來通知控件應該轉移到first(),但是不會發生。
我下面的MSDN以下https://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx
任何幫助可以理解爲信息爲什麼s
線程不是轉向控制f
線程與第二Monitor.Pulse()
()
Follwinng是我的主要()
test t = new test();
test1 t1 = new test1();
Thread f = new Thread(new ThreadStart(t.first));
Thread s = new Thread(new ThreadStart(t1.second));
f.Start();
s.Start();
f.Join();
s.Join();
即使這個問題得到解決,這裏仍然有一場比賽,'second'假定'first'獲得了鎖,並且在'second'獲得鎖之前進入了'Wait'。 (因爲'沒有任何人的脈搏'等待'丟棄) –
@Damien_The_Unbeliever但是這個答案工作正常。 – Alex
@Alex - 它會 - *一些*的時間。這是一場比賽,看看哪個線程實際上首先執行'lock(this)'行,而不是*保證*。 –