| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 591 人关注过本帖
标题:请教多线程问题(请点评下程序中多线程的用法是否正确?)
只看楼主 加入收藏
wrljl
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2007-9-28
收藏
 问题点数:0 回复次数:1 
请教多线程问题(请点评下程序中多线程的用法是否正确?)

小弟最近在学多线程问题,请教各位下面程序中,多线程的用法是否正确?还有为什么当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);
}
}
}
}
}

搜索更多相关主题的帖子: 线程 用法 点评 
2007-09-28 08:42
jxnuwy04
Rank: 2
等 级:新手上路
威 望:4
帖 子:768
专家分:0
注 册:2006-9-15
收藏
得分:0 

线程的执行,有一定的时间片,应该是跟cpu的计算水平有关吧


------------------不为别的,就为你,我的理想!-----------------
2007-09-29 12:23
快速回复:请教多线程问题(请点评下程序中多线程的用法是否正确?)
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.013849 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved