您的位置:首页 > 编程语言 > C#

C# 多线程研究1——线程同步(发牌模拟)

2010-10-01 20:51 246 查看
最近公司部门领导让我做一个局域网控制的东东,要求有一些IM的功能。于是乎起了一个后台线程,监听来自其他客户端和服务器的消息。开始研究多线程来。这些经验要记下来才好。希望有达人看到这些线程研究的文章,给出批评和建议。

发牌程序

一个线程发牌,每次生成四个;

四个线程得到牌,每个线程得到一个;

然后继续,直到54张牌发完。

实际上有生产者、消费者的味道。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestThread
{
class putAndGet
{
private List<int> arrList = new List<int>();
public int counts = 1;//当前发到那张牌
public int semp = 1;//这个可否叫信号量
Random rand = new Random();//随机出每个得牌线程能得到的牌的序号
/// <summary>
/// 我把它叫消费者线程
/// </summary>
public void Get()
{
lock (arrList)
{
Monitor.Pulse(arrList);
while (Monitor.Wait(arrList, 1000))//等待
{
if (arrList.Count > 0 && semp.ToString() == Thread.CurrentThread.Name)//有牌生成,且轮到“我”了
{
int index = rand.Next(0, arrList.Count);
Console.WriteLine("线程"+Thread.CurrentThread.Name+" 得到的值:"+arrList[index]);
arrList.RemoveAt(index);
semp++;
if (semp == 5)
{
semp = 1;
}
}
Monitor.PulseAll(arrList);//唤醒其他所有线程
}

}
}
/// <summary>
/// 生产者,每次出四张牌
/// </summary>
public void put()
{
lock (arrList)
{
while (counts < 54)//生成54张牌
{
Monitor.Wait(arrList);//等待
if (arrList.Count == 0)
{
for (int i = 0; i < 4; i++)//生成四张牌
{
arrList.Add(counts);
counts++;
}
Monitor.PulseAll(arrList);//唤醒其他线程
}
}
}
}
}
}


在Main函数中,启动发牌线程和得牌线程:

static void Main(string[] args)
{
putAndGet pThread = new putAndGet();
Thread cardProducer = new Thread(new ThreadStart(pThread.put));
cardProducer.Start();//发牌线程启动
Thread t1 = new Thread(new ThreadStart(pThread.Get));
t1.Name = "1";
t1.Start();
Thread t2 = new Thread(new ThreadStart(pThread.Get));
t2.Name = "2";
t2.Start();
Thread t3 = new Thread(new ThreadStart(pThread.Get));
t3.Name = "3";
t3.Start();
Thread t4 = new Thread(new ThreadStart(pThread.Get));
t4.Name = "4";
t4.Start();//4个子线程启动

cardProducer.Join();//阻塞主线程
t1.Join();
t2.Join();
t3.Join();
t4.Join();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: