您的位置:首页 > 职场人生

一个多线程的面试题

2013-02-28 23:00 169 查看
面试题的大意是:启动三个线程,分别打印A、B、C,每个打印十遍,打印的顺序为ABCABCABC...

我的思路是用了线程同步技术中的事件ManualResetEvent事件,用到方法有

Set 将事件的状态设置为终止状态,允许一个或多个等待的线程继续

Reset 将事件的状态设置为非终止状态,导致线程阻止

WaitOne 阻止当前线程,直到当前 WaitHandle收到信号

代码如下,如有不足之处,敬请指教,再次多谢。

static ManualResetEvent manA;
static ManualResetEvent manB;
static ManualResetEvent manC;
static void Main(string[] args)
{
manA = new ManualResetEvent(false);
manB = new ManualResetEvent(false);
manC = new ManualResetEvent(false);

Thread threadA = new Thread(MethodA);
threadA.Start();
Thread threadB = new Thread(MethodB);
threadB.Start();

Thread threadC = new Thread(MethodC);
threadC.Start();

Console.ReadLine();
}

private static void MethodA()
{
for (int i = 0; i < 10; i++)
{
Console.Write("A");
manB.Set();   //终止manB事件,启动一个或多个线程
manA.Reset(); //更改manA事件状态为非终止状态,并阻止
manA.WaitOne();  //阻止线程,等待WaitHandle的信号
}
}
private static void MethodB()
{
manB.WaitOne();
for (int i = 0; i < 10; i++)
{
Console.Write("B");
manC.Set();
manB.Reset();
manB.WaitOne();
}
}

private static void MethodC()
{
manC.WaitOne();
for (int i = 0; i < 10; i++)
{
Console.Write("C");
manA.Set();
manC.Reset();
manC.WaitOne();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: