网页资讯视频图片知道文库贴吧地图采购
进入贴吧全吧搜索

 
 
 
日一二三四五六
       
       
       
       
       
       

签到排名:今日本吧第个签到,

本吧因你更精彩,明天继续来努力!

本吧签到人数:0

一键签到
成为超级会员,使用一键签到
一键签到
本月漏签0次!
0
成为超级会员,赠送8张补签卡
如何使用?
点击日历上漏签日期,即可进行补签。
连续签到:天  累计签到:天
0
超级会员单次开通12个月以上,赠送连续签到卡3张
使用连续签到卡
12月15日漏签0天
c#吧 关注:188,683贴子:823,970
  • 看贴

  • 图片

  • 吧主推荐

  • 视频

  • 游戏

  • 2回复贴,共1页
<<返回c#吧
>0< 加载中...

关于两个线程交替出现的机制问题。

  • 取消只看楼主
  • 收藏

  • 回复
  • lyfuci
  • c#求知者
    5
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
namespace ThreadTest_2
{
class People
{
public string Name {get; set;}
public string Gender { get; set; }
}
class Producer
{
readonly AutoResetEvent autoResetEvent;
internal People people { get; set; }
public Producer(People people, AutoResetEvent mre)
{
this.people = people;
this.autoResetEvent = mre;
}
public void Produce()
{
for (int i = 0; i < 20; i++)
{
autoResetEvent.WaitOne();
if (i % 2 == 0)
{
people.Name = "春哥";
Thread.Sleep(1);
people.Gender = "男";
Thread.Sleep(1);
}
else
{
people.Name = "凤姐";
Thread.Sleep(1);
people.Gender = "女";
Thread.Sleep(1);
}
autoResetEvent.Set();
}
}
}
class Comsumer
{
readonly AutoResetEvent autoResetEvent;
internal People people { get; set; }
public Comsumer(People people, AutoResetEvent mre)
{
this.people = people;
this.autoResetEvent = mre;
}
public void Comsume()
{
for (int i = 0; i < 20; i++)
{
autoResetEvent.WaitOne();
if (people.Name == "凤姐" && people.Gender != "女")
{
Console.WriteLine("fail ");
break;
}
if (people.Name == "春哥" && people.Gender != "男")
{
Console.WriteLine(" fail");
break;
}
Console.WriteLine(people.Name + "->" + people.Gender+i);
autoResetEvent.Set();
}
}
}
class Program
{
static void Main()
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
People people = new People();
Producer producer = new Producer(people, autoResetEvent);
Comsumer comsumer = new Comsumer(people, autoResetEvent);
Thread a = new Thread(producer.Produce);
Thread b = new Thread(comsumer.Comsume);
a.Start();
b.Start();
autoResetEvent.Set();
a.Join();
b.Join();
Console.ReadKey();
}
}
}
其实单个函数功能我大概都调试懂了,但是不要怪我蠢,我就是如何保证第一个是先运行produce,然后,交替运行的看不懂,一开始两个线程开始了,然后进入for语句,等待着宠幸,然后主线程set()函数起作用,起作用不是应该produc和comsume同时开始进行吗,这个里面是怎么确定一定是交替出现的啊,莫非是两个先后顺序的join()????我试了一下,删除join也没有一点点影响,或者有影响只不过是观察不到的罢了,我就是不清楚这个为何能保证交替出现。


  • lyfuci
  • c#求知者
    5
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
自己顶。。。。


2025-12-15 11:38:37
广告
不感兴趣
开通SVIP免广告
  • lyfuci
  • c#求知者
    5
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
再顶。


登录百度账号

扫二维码下载贴吧客户端

下载贴吧APP
看高清直播、视频!
  • 贴吧页面意见反馈
  • 违规贴吧举报反馈通道
  • 贴吧违规信息处理公示
  • 2回复贴,共1页
<<返回c#吧
分享到:
©2025 Baidu贴吧协议|隐私政策|吧主制度|意见反馈|网络谣言警示