上例程
背景:张三李四互砍,你一刀,我一刀,公平互砍
using System;
using System.Threading;
namespace ConsoleApp1
{
internal class Program
{
private static void Main(string[] args)
{
AutoResetEvent AManSuccess = new AutoResetEvent(true);
AutoResetEvent BManSuccess = new AutoResetEvent(true);
Man manOne = new Man("张三", AManSuccess, BManSuccess,1000);
Man manTwo = new Man("李四", BManSuccess, AManSuccess,500);
Thread thread1 = new Thread(new ThreadStart(manOne.Cut));
Thread thread2 = new Thread(new ThreadStart(manTwo.Cut));
thread1.Start();
thread2.Start();
//while (true)
//{
// Console.ReadKey();
// BManSuccess.Set();
//}
}
}
public class Man
{
private string name = "";
public Man(string name, AutoResetEvent safeManSuccess, AutoResetEvent friendsManSuccess,int delaytime)
{
this.name = name;
this.safeManSuccess = safeManSuccess;
this.friendsManSuccess = friendsManSuccess;
this.delaytime = delaytime;
}
private AutoResetEvent safeManSuccess = null;
private AutoResetEvent friendsManSuccess = null;
private int delaytime = 0;
public void Cut()
{
int index = 0;
while (index++ < 30)
{
friendsManSuccess.WaitOne();
Console.WriteLine(name + "砍第" + index + "刀");
Thread.Sleep(delaytime);
safeManSuccess.Set();
}
}
}
}
运行结果
用法
set():触发
waitOne():阻塞等待
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/51782.html