zoukankan      html  css  js  c++  java
  • 生产者,消费者线程

    代码

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

    namespace TestThreadDemos
    {
        
    /// <summary>
        
    /// 生产者消费者队列
        
    /// </summary>
        public class ProducerConsumerQueue : IDisposable
        {
            
    private Thread worker;
            
    private EventWaitHandle wh;
            
    private Queue<string> workQueue;
            
    private object locker;
            
    public ProducerConsumerQueue()
            {
                wh 
    = new AutoResetEvent(false);
                workQueue 
    = new Queue<string>();
                locker 
    = new object();
                worker 
    = new Thread(Work);
                worker.Start();
            }

            
    private void Work()
            {
                
    while (true)
                {
                    
    string outTask = null;
                    
    lock (locker)
                        
    if (workQueue.Count > 0)
                            outTask 
    = workQueue.Dequeue();
                    
    if (outTask == nullreturn;
                    
    if (outTask != null)
                    {
                        Console.WriteLine(
    "输出的任务" + outTask);
                        Thread.Sleep(
    5000);
                    }
                    
    else
                        wh.WaitOne();
                }
            }

            
    public void Dispose()
            {
                EnWorkQueue(
    null);
                worker.Join();
                wh.Close();
            }

            
    public void EnWorkQueue(string task)
            {
                
    if (workQueue != null)
                {
                    
    lock (locker)
                        workQueue.Enqueue(task);
                    wh.Set();
                }
            }
        }
    }
  • 相关阅读:
    【linux】——man中文帮助手册安装
    【linux】——centos 分辨率配置
    松本行弘访谈录
    图灵热点之阅读篇——五月图书推荐
    《Linux/Unix 设计思想》的翻译细节讨论
    一本书的推荐序——写在《思考的乐趣》即将上市之际
    带您走进七周七语言的程序世界
    作者为何要创作《网站转换率优化之道》
    Apress水果大餐——移动开发
    “怪诞”的数学天才
  • 原文地址:https://www.cnblogs.com/csharponworking/p/1643381.html
Copyright © 2011-2022 走看看