博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#线程--生产者和消费者
阅读量:7145 次
发布时间:2019-06-29

本文共 2165 字,大约阅读时间需要 7 分钟。

using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Security;using System.Text;using System.Threading;namespace ConsoleApp{    class Test    {        static void Main()        {            product pro = new product();            setProduct set = new setProduct(pro, 100);            getProduct get = new getProduct(pro, 100);            Thread producer = new Thread(new ThreadStart(set.run));            Thread consumer = new Thread(new ThreadStart(get.run));            producer.Start();            consumer.Start();            Console.ReadLine();        }    }    class getProduct    {        private product pro;        private int quality = 0;        public getProduct(product pro,int request)        {            this.pro = pro;            quality = request;        }        public void run()        {            for (int i = 0; i < quality; i++)            {                pro.getProduct();            }        }    }    class setProduct    {        private product pro;        private int quality = 0;        public setProduct(product pro, int request)        {            this.pro = pro;            quality = request;        }        public void run()        {            for (int i = 0; i < quality; i++)            {                pro.setProduct(i);            }        }     }    class product    {        private int cellContents;        private bool setflage = false;        public int setProduct(int n)        {            lock (this)            {                if (setflage)                {                        Monitor.Wait(this);                }                Console.WriteLine("生产中。。。"+n);                cellContents = n;                setflage = true;                Monitor.Pulse(this);            }            return cellContents;        }        public void getProduct()        {            lock (this)            {                if (!setflage)                {                   Monitor.Wait(this);                }                Console.WriteLine("消耗中。。。" + cellContents);                setflage = false;                Monitor.Pulse(this);            }        }    }}
View Code

 

转载地址:http://gjgrl.baihongyu.com/

你可能感兴趣的文章
汇编语言描述
查看>>
移动开发学习记录
查看>>
Source Insight 使用
查看>>
【转】Oracle Freelist和HWM原理及性能优化
查看>>
数据结构——树状数组
查看>>
reloc: Permission denied
查看>>
2015 ICPC 长春
查看>>
java编写本月日历
查看>>
在腾讯开放平台上,同一个QQ号码在不通的APP里返回的OpenID不一样且完全没有关联,这样的设计是处于什么考虑?...
查看>>
java学习(一)((java编程思想)待补充)—— ·对象
查看>>
Oracle GoldenGate实现数据库同步
查看>>
ural 1356. Something Easier(数论,哥德巴赫猜想)
查看>>
使用单元素枚举实现单例
查看>>
前端基本知识
查看>>
将excel中的数据转为json格式
查看>>
Poedu_项目2_Lesson005 课堂笔记
查看>>
字典操作
查看>>
实验2
查看>>
使用source创建一个新项目(将本地项目文件和github远程库链接)
查看>>
运行问题,如何修改APACHE的监听端口和密码
查看>>