0
大圖是從1
打印一個Thread t
到某個值,然後暫停執行,取決於signal (ManualResetEvent)
期間執行另一個線程s
執行。 s
完成後,它sets the signal
。因此,T
恢復執行。預期上半年直到線程t
暫停時signal
是在WorkOnKeyReached
reset
帶線程事件處理
class A
{
int key;
int temp;
public A(int x)
{
key = x;
}
public EventHandler eventHandler;
private void onKeyReached(object sender, EventArgs e)
{
eventHandler(this, e);
}
public int Temp
{
get { return temp; }
set
{
if (value == temp) return;
else if (temp == key)
onKeyReached(this, EventArgs.Empty);
else
temp = value;
}
}
}
class Test
{
static A a = new A(500);
//signal to pause or resume threads
static ManualResetEvent signal = new ManualResetEvent(true);
static void Main()
{
a.eventHandler += WorkOnKeyReached;
Thread t = new Thread(F);
t.Start();
}
static void F()
{
for (int i = 0; i < 1000; i++)
{
a.Temp = i;
//when a.Temp == a.Key, a.OnkeyReached() is fired.
signal.WaitOne();
Console.WriteLine(a.Temp);
}
}
static void WorkOnKeyReached(object sender, EventArgs e)
{
signal.Reset();
Thread s = new Thread(() =>
{
Console.WriteLine("Doing something else...");
Thread.Sleep(3000);
Console.WriteLine("Done..");
signal.Set();
});
s.Start();
}
}
計劃工作。 然而WorkOnKeyReached
完成後,我set
的signal
預期t
繼續。
輸出繼電器:
1
2
..
500
Doing something else...
Done.
500
Doing something else...
Done.
誰能幫助解釋這一現象?我只是在玩線程和其他東西。
我可以告訴你,現在對A類臨時二傳手不是線程安全 – William
爲什麼'a.Temp = i'不安全?我明白只有1個線程執行該行。 –