using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Produce_and_Consumer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
allgoods = new int[10];
}
Thread consumer;
Thread producer;
object store;
int sum = 2;
int goods = 0;
int[] allgoods;
int totaltimes = 5;//模拟操作的次数
int times1 = 0;
int times2 = 0;
int produce_speed = 1;
int consume_speed = 1;
delegate void dele();
private void consume()
{
while (times1 != totaltimes)
{
if (goods > 0)
{
lock (store)
{
Thread.Sleep(1000 * consume_speed);
consume_label.Text += string.Format("商品{0}\n", times1 + 1);
times1++;
goods--;
this.Refresh();
}
}
}
}
private void produce()
{
while (times2 != totaltimes)
{
if (goods < sum)
{
lock (store)
{
Thread.Sleep(1000 * produce_speed);
produce_label.Text += string.Format("商品{0}\n", times2 + 1);
times2++;
goods++;
this.Refresh();
//Interlocked.Increment(ref goods);
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
consumer = new Thread(invokeforconsumer);
producer = new Thread(invokeforproducer);
store = new object();
producer.Start();
consumer.Start();
}
private void invokeforconsumer()
{
dele forconsumer = new dele(consume);
this.BeginInvoke(forconsumer);
}
private void invokeforproducer()
{
dele forproducer = new dele(produce);
this.BeginInvoke(forproducer);
}