Beispiel #1
0
        public static void RunSync()
        {
            // 配置结构,该结构包含线程同步
            // 所需的事件信息。
            SyncEvents syncEvents = new SyncEvents();

            // 泛型队列集合用于存储要制造和使用的
            // 项。此例中使用的是“int”。
            Queue <int> queue = new Queue <int>();

            // 创建对象,一个用于制造项,一个用于
            // 使用项。将队列和线程同步事件传递给
            // 这两个对象。
            Console.WriteLine("Configuring worker threads...");
            Producer producer = new Producer(queue, syncEvents);
            Consumer consumer = new Consumer(queue, syncEvents);

            // 为制造者对象和使用者对象创建线程
            // 对象。此步骤并不创建或启动
            // 实际线程。
            Thread producerThread = new Thread(producer.ThreadRun);
            Thread consumerThread = new Thread(consumer.ThreadRun);

            // 创建和启动两个线程。
            Console.WriteLine("Launching producer and consumer threads...");
            producerThread.Start();
            consumerThread.Start();

            // 为制造者线程和使用者线程设置 10 秒的运行时间。
            // 使用主线程(执行此方法的线程)
            // 每隔 2.5 秒显示一次队列内容。
            for (int i = 0; i < 4; i++)
            {
                Thread.Sleep(500);
                ShowQueueContents(queue);
            }

            // 向使用者线程和制造者线程发出终止信号。
            // 这两个线程都会响应,由于 ExitThreadEvent 是
            // 手动重置的事件,因此除非显式重置,否则将保持“设置”。
            Console.WriteLine("Signaling threads to terminate...");
            syncEvents.ExitThreadEvent.Set();

            // 使用 Join 阻塞主线程,首先阻塞到制造者线程
            // 终止,然后阻塞到使用者线程终止。
            Console.WriteLine("main thread waiting for threads to finish...");
            producerThread.Join();
            consumerThread.Join();
        }
Beispiel #2
0
 public Consumer(Queue <int> q, SyncEvents e)
 {
     _queue      = q;
     _syncEvents = e;
 }
Beispiel #3
0
 public Producer(Queue <int> q, SyncEvents e)
 {
     _queue      = q;
     _syncEvents = e;
 }