200分求一个多线程链式队列的控制台程序

wang520d 2008-03-12 02:37:15
要求:一:2个线程往队列写数据,1个线程从队列里面读数据 读取的是最后一个线程写的数据;(在控制台输出读和写的数据)
二:能区分是哪个线程写的数据
三:用exit命令结束线程

...全文
324 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wang520d 2008-03-12
  • 打赏
  • 举报
回复
修改了一下等待时间 果然正常结束线程
wang520d 2008-03-12
  • 打赏
  • 举报
回复
不好意思 白天一直在忙。。。

看到上面仁兄的代码 大开眼界
逻辑处理非常严谨

可是当输入exit 结束线程时 好像不太好用 是不是因为等待的时间太短呢?
yilanwuyu123 2008-03-12
  • 打赏
  • 举报
回复
有情UP 持续关注
jilate 2008-03-12
  • 打赏
  • 举报
回复
要点有3
1、采用队列等适合实际需要的数据结构
2、设置标志确定退出
3、对全局资源访问时加锁

楼上的都做好了
大宇_ 2008-03-12
  • 打赏
  • 举报
回复
ThreadPool.QueueUserWorkItem,排入队列执行,ThreadPool.SetMaxThreads这个控制数目,我在CODEPROJECT上见过一个例子回头找找
jinjazz 2008-03-12
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{

//堆栈是后进先出的
static System.Collections.Stack stack = new System.Collections.Stack();
//信号量控制线程
static System.Threading.ManualResetEvent obj = new System.Threading.ManualResetEvent(false);

//写入的对象
public class Data
{
public Guid ID = Guid.NewGuid();
public string ThreadName = System.Threading.Thread.CurrentThread.Name;

public override string ToString()
{
return string.Format("{0}生成的{1}", ThreadName, ID);
}

}

static void Main(string[] args)
{
obj.Reset();
System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(wirteData));
System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(wirteData));
System.Threading.Thread t3 = new System.Threading.Thread(new System.Threading.ThreadStart(readData));
t1.Name = "w1";
t2.Name = "w2";
t3.Name = "r1";

t1.Start();
t2.Start();
t3.Start();

//等待输入
if (Console.ReadLine().ToLower() == "exit")
{
obj.Set();
Console.WriteLine("退出!");
}
}
//
static Random rand = new Random(100);
private static void wirteData()
{
//线程等待时间
int i = rand.Next(3000, 4000);
while (obj.WaitOne(i, false) == false)
{
Data data = new Data();
lock (stack)
{
stack.Push(data);
}
Console.WriteLine("写入:"+data.ToString());
}
Console.WriteLine("退出!");
}

private static void readData()
{
int i = rand.Next(2000, 3000);
while (obj.WaitOne(i, false) == false)
{
lock (stack)
{
if (stack.Count > 0)
{
Data data = stack.Pop() as Data;
Console.WriteLine("读取:" + data.ToString());
}
else
{
Console.WriteLine("无数据!");
}

}

}
}
}
}
wang520d 2008-03-12
  • 打赏
  • 举报
回复
等待ing...........

110,555

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧