Flower

using System;
using System.Threading;

public class TestMain
{
    private static ManualResetEvent ent = new ManualResetEvent(false);
    public static void Main33()
    {
        Boy sender = new Boy(ent);
        //Thread th = new Thread(new ThreadStart(sender.SendFlower));
        //th.Start();
        //ent.WaitOne(); //等待工作 
        for (int i = 0; i < 3; i++)
        {
            ent.Reset();
            Thread th = new Thread(new ThreadStart(sender.SendFlower));
            th.Start();
            ent.WaitOne();
            Console.WriteLine("收到了吧,花是我送嘀:)\r\n\r\n");
        }
    }
}
public class Boy
{
    ManualResetEvent ent;
    public Boy(ManualResetEvent e)
    {
        ent = e;
    }
    public void SendFlower()
    {
        //Console.WriteLine("正在送花的途中");
        for (int i = 0; i < 10; i++)
        {
            Thread.Sleep(200);
            Console.Write("..");
        }
        Console.WriteLine("\r\n花已经送到MM手中了,boss");
        ent.Set(); //通知阻塞程序 
    }
}


//而AutoResetEvent类故名思意,就是在每次Set完之后自动Reset。让执行程序重新进入阻塞状态。 即AutoResetEvent.Set() 相当于 ManualResetEvent.Set() 之后又立即 ManualResetEvent.Reset()
public class TestMain11
{
    private static AutoResetEvent ent = new AutoResetEvent(false);
    public static void Main66()
    {
        Boy11 sender = new Boy11(ent);
        for (int i = 0; i < 3; i++)
        {
            Thread th = new Thread(new ThreadStart(sender.SendFlower));
            th.Start();
            ent.WaitOne(); //等待工作 
            Console.WriteLine("收到了吧,花是我送嘀:)\r\n\r\n");
        }
        Console.ReadLine();
    }
}

public class Boy11
{
    AutoResetEvent ent;
    public Boy11(AutoResetEvent e)
    {
        ent = e;
    }
    public void SendFlower()
    {
        Console.WriteLine("正在送花的途中");
        for (int i = 0; i < 10; i++)
        {
            Thread.Sleep(200);
            Console.Write("..");
        }
        Console.WriteLine("\r\n花已经送到MM手中了,boss");
        ent.Set(); //通知阻塞程序,这里的效果相当于 ManualResetEvent的Set()方法+Reset()方法 
    }
}

 

posted on 2011-11-15 22:30  breakpoint  阅读(105)  评论(0编辑  收藏  举报

导航