zoukankan      html  css  js  c++  java
  • 生产者消费者模式

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace M_生产者消费者模式
    {
        class Program
        {
            static void Main(string[] args)
            {
                
               Prodeuct[] produs=new Prodeuct[100];
    
              object m_lock=new object();
               int index = 0;
                //定义5个生产者
                for(int i =0;i<5;i++)
                {
                    new Thread(() => {
                        while (true)
                        {
                            lock (m_lock)
                            {
                                if (index < 99)
                                {
                                    Prodeuct p = new Prodeuct();
                                    produs[index] = p;
                                    Console.WriteLine("生成一个产品" + Thread.CurrentThread.ManagedThreadId);
                                    index++;
                                }
                            }
                          
                        }
                                     
                    }).Start();
                    //定义5个消费者
                    for (int j = 0; j < 5; j++)
                    {
                        new Thread(() =>
                        {
    
                            while (true)
                            {
                                lock (m_lock)
                                {
                                    if (index > 0)
                                    {
                                        Prodeuct p = produs[index - 1] = null;
                                        Console.WriteLine("消耗一个产品" + Thread.CurrentThread.ManagedThreadId);
                                        index--;
                                    }
                                }
                                Thread.Sleep(100);
                            }
    
    
                        }).Start();
    
                    }
    
                }
            }
           public class Prodeuct
           {
    
           }
        }
    }
    

      

  • 相关阅读:
    Cocos2d-x游戏移植到Android平台
    Alice and Bob
    Hamming Codes
    Fire逃生
    Java中面向对象的理解
    常见的几个算法
    数组的介绍
    Java 中的数据类型
    Java 初相识
    JavaScript 数据类型 (续)
  • 原文地址:https://www.cnblogs.com/cdaq/p/4938576.html
Copyright © 2011-2022 走看看