您的位置:首页 > 其它

线程同步 ManualResetEvent

2009-12-03 22:26 423 查看

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ThreadEvent
{
class Program
{
static ManualResetEvent m_evt1;
static ManualResetEvent m_evt2;
public static void fnFirstThread()
{
Console.WriteLine("线程 1 启动");
Thread.Sleep(1200);
Console.WriteLine("线程 1 执行:");
for (int i = 0; i < 40; i++)
{
Console.Write(".");
Thread.Sleep(200);
}
Console.WriteLine("/r/n线程1停止");
m_evt1.Set();//设置事件,启动线程2
}

public static void fnSecondThread()
{
Console.WriteLine("线程 2 等待线程1 执行完毕==");
m_evt1.WaitOne();
Thread.Sleep(200);
Console.WriteLine("线程 2 启动");
Thread.Sleep(200);
Console.Write("线程2执行:");
for (int i = 0; i < 20; i++)
{
Console.Write(".");
Thread.Sleep(200);
}
Console.WriteLine("/r/n线程2停止");
m_evt2.Set();
}

public static void fnThirdthread()
{
Console.WriteLine("线程 3 等待线程2执行完毕==");
m_evt2.WaitOne();
Thread.Sleep(1200);
Console.WriteLine("线程3启动");
Thread.Sleep(1200);
Console.Write("线程3执行");
for (int i = 0; i < 20; i++)
{
Console.Write(".");
Thread.Sleep(200);
}
Console.WriteLine("/r/n线程3停止");
}

static void Main(string[] args)
{
m_evt1 = new ManualResetEvent(false);
m_evt2 = new ManualResetEvent(false);
Thread tFirst = new Thread(new ThreadStart(fnFirstThread));
Thread tSecond = new Thread(new ThreadStart(fnSecondThread));
Thread tThird = new Thread(new ThreadStart(fnThirdthread));
tThird.Start();
tFirst.Start();
tSecond.Start();
tThird.Join();//等待结束,,只需要等待第三个线程运行结束
Console.WriteLine ("线程3运行结束");
Console.WriteLine("线程1状态:{0}", tFirst.ThreadState.ToString());
Console.WriteLine("线程2状态:{0}", tSecond.ThreadState.ToString());
Console.WriteLine("按任意键退出");
Console.ReadKey();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: