用一個三國演義的典故來寫段示例代碼:
話說曹操率領80W大軍準備圍剿劉備和孫權,面對敵衆我寡的情況,諸葛亮與周瑜想到了一個妙計,用裝滿火藥桶的大船去衝擊曹操連在一起的戰船,計劃都安排好了,可謂“萬事俱備只欠東風”。
using System;
using System.Threading;
namespace Test
{
class Program
{
//默認信號爲不發送狀態
private staticManualResetEvent mre = new ManualResetEvent(false);
static void Main(string[]args)
{
EastWind wind = new EastWind(mre);
//啓動東風的線程
Thread thd = new Thread(newThreadStart(wind.WindComming));
thd.Start();
mre.WaitOne();//萬事俱備只欠東風,事情卡在這裏了,在東風來之前,諸葛亮沒有進攻
//東風到了,可以進攻了
Console.WriteLine("諸葛亮大吼:東風來了,可以進攻了,滿載燃料的大船接着東風衝向曹操的戰船");
Console.ReadLine();
}
}
///
/// 傳說中的東風
///
class EastWind
{
ManualResetEvent _mre;
///
/// 構造函數
///
publicEastWind(ManualResetEvent mre)
{
_mre = mre;
}
///
/// 風正在吹過來
///
public void WindComming()
{
Console.WriteLine("東風正在吹過來");
for (int i = 0; i <= 5; i++)
{
Thread.Sleep(500);
Console.WriteLine("東風吹啊吹,越來越近了...");
}
Console.WriteLine("東風終於到了");
//通知諸葛亮東風已到,可以進攻了,通知阻塞的線程可以繼續執行了
_mre.Set();
}
}
}
運行結果: