请教大家写一个线程

fihuang 2009-03-18 05:15:16
看书看了半天也没看懂。

一个队列Queue<string> q和两个线程。
其中一个线程写入数据到q,另一个从q取出数据。
主线程可以写入数据,再写一个线程读出数据,我这个想法有错吗?麻烦大家些段简单的代码解释一下!
万分感谢!
...全文
51 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
fihuang 2009-03-18
  • 打赏
  • 举报
回复
高手呢
fihuang 2009-03-18
  • 打赏
  • 举报
回复
我照葫芦画瓢写了个,怎么看怎么不对!本来多线程是为了读取速度更快,我写的代码没有体现出速度,反而变慢了!怎么回事儿啊!
[code=C#]
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static Queue<string> q = new Queue<string>();
static void Main(string[] args)
{
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(getData));
for (int i = 1; i <= 100000000; i++)
{
if (i % 10000000 == 0)
{
lock (q)
{
q.Enqueue((i / 10000000).ToString());
}
Console.WriteLine("i:" + i / 10000000);
//System.Threading.Thread.Sleep(1 * 1000);
//Console.WriteLine(q.Dequeue());
}
}
}

static void getData(object o)
{
while (true)
{
if (q.Count > 0)
{
Console.WriteLine(q.Dequeue());
}
}
}
}
}
code]
fihuang 2009-03-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 showyoumymercy 的回复:]
要monitor
[/Quote]lock(q)可以吗
EsMo 2009-03-18
  • 打赏
  • 举报
回复
要monitor

111,126

社区成员

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

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

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