读写同步:AutoResetEvent:ReadThread After WriteThread

来源:互联网 发布:java等于号 编辑:程序博客网 时间:2024/06/05 05:00

using System;
using System.Threading;

namespace AutoResetEvent_Examples
{
    class MyMainClass
    {
        const int numIterations = 10;
        static AutoResetEvent myResetEvent = new AutoResetEvent(false);
        static int number;

        static void Main()
        {
            Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
            myReaderThread.Name = "ReaderThread";
            myReaderThread.Start();

            for (int i = 1; i <= numIterations; i++)
            {
                Console.WriteLine("Writer thread writing value: {0}", i);
                number = i;
                myResetEvent.Set();
                Thread.Sleep(0);
            }
            myReaderThread.Abort();
            Console.ReadKey();
        }

        static void MyReadThreadProc()
        {
            while (true)
            {
                myResetEvent.WaitOne();
                Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number);
            }
        }
    }
}

原创粉丝点击