小弟最近在学多线程问题,请教各位下面程序中,多线程的用法是否正确?还有为什么当Thread.Sleep();的休眠时间设定比较大时,显示结果不会从1,3,5,7,9......开始?
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
namespace 线程实现
{
class Program
{
static void Main(string[] args)
{
MonitorSample monitor = new MonitorSample();
Thread producer = new Thread(new ThreadStart(monitor.Producer));
Thread pd = new Thread(new ThreadStart(monitor.pd));
Thread consumer = new Thread(new ThreadStart(monitor.Consumer));
producer.Start();
pd.Start();
consumer.Start();
Thread.Sleep(200);
producer.Abort();
pd.Abort();
consumer.Abort();
Console.ReadLine();
}
}
public class MonitorSample
{
private Queue _queue = new Queue();
public void Producer()
{
int a = 1;
while (true)
{
Thread.Sleep(0);
ArrayList al = new ArrayList();
while (al.Count < 5)
{
if (a%2 != 0)
{
al.Add(a);
a++;
}
else
{
a++;
}
}
lock (_queue)
{
_queue.Enqueue(al);
Monitor.Pulse(_queue);
Monitor.Wait(_queue);
}
}
}
public void pd()
{
int i = 1;
while (true)
{
Thread.Sleep(0);
ArrayList al1 = new ArrayList();
while(al1.Count < 5)
{
if(i%2 == 0)
{
al1.Add(i);
i++;
}
else
{
i++;
}
}
lock (_queue)
{
_queue.Enqueue(al1);
Monitor.Pulse(_queue);
Monitor.Wait(_queue);
}
}
}
public void Consumer()
{
lock (_queue)
{
while (true)
{
Monitor.Pulse(_queue);
Monitor.Wait(_queue);
ArrayList qal = (ArrayList)_queue.Dequeue();
for (int j = 0; j < qal.Count; j++ )
{
Console.WriteLine(String.Format("消费:{0}", qal[j]));
Console.WriteLine();
}
Monitor.Pulse(_queue);
}
}
}
}
}