线程同步对象的使用方法

2008-08-15 10:21:11.0     浏览:1013     来源:中国IT实验室
关键词:  线程同步     使用方法  

举个送花给N个MM的例子:

  using System;

  using System.Threading;

  public class TestMain

  {

  private static AutoResetEvent ent = new AutoResetEvent(false);

  public static void Main()

  {

  Boy sender = new Boy(ent);

  for (int i = 0; i <3; i++)

  {

  Thread th = new Thread(new ThreadStart(sender.SendFlower));

  th.Start();

  ent.WaitOne(); //等待工作

  Console.WriteLine("收到了吧,花是我送嘀:) ");

  }

  Console.ReadLine();

  }

  }

  public class Boy

  {

  AutoResetEvent ent;

  public Boy(AutoResetEvent e)

  {

  ent = e;

  }

  public void SendFlower()

  {

  Console.WriteLine("正在送花的途中");

  for (int i = 0; i <10; i++)

  {

  Thread.Sleep(200);

  Console.Write("..");

  }

  Console.WriteLine(" 花已经送到MM手中了,boss");

  ent.Set(); //通知阻塞程序,这里的效果相当于 ManualResetEvent的Set()方法+Reset()方法

  }

  }

[上一页]   [第1页]   [第2页]   [第3页]   [第4页]   [第5页]   [下一页]