????????????????????????t1??t2??t3??t4????4???????д??????????t1???д??“1”??t2???д??“2”??t3???д??“3”??t4???д??“4”????4?????A??B??C??Dд??????????:
????A??123412341234.....
????B??234123412341....
????C??341234123412....
????D??412341234123....
????????????£?????A?????t1д??“1”???????????t2??д“2”??????t1???D????????д“1”??????????
????1. ????????????
??????????????????????????t2??д“2”???????????????????? Set ???????????D?????д“1”?????????????????????? WaitOne ???????±???????4?? AutoResetEvent ?????????
class Program
{
private static List<StreamWriter> _sws;
private static List<AutoResetEvent> _whs;
private static void Main(string[] args)
{
var fileNames = new List<string> {"A"?? "B"?? "C"?? "D"};
// ????????????
fileNames.ForEach(name =>
{
if (!File.Exists(name))
File.Create(name).Close();
else
{
using (var sw = new StreamWriter(name))
sw.Write("");
}
});
_sws = fileNames.Select(File.AppendText).ToList();
// ???????д?????????????
_whs = fileNames.Select(name => new AutoResetEvent(false)).ToList();
// ????????4????????????
var threads = new List<Thread> {
new Thread(() => Work(1))?? new Thread(() => Work(2))?? new Thread(() => Work(3))?? new Thread(() => Work(4))
};
threads.ForEach(t => t.Start());
// ?????????????? StreamWrite
threads.ForEach(t => t.Join());
Console.WriteLine("????????");
_sws.ForEach(sw => sw.Close());
}
static void Work(int threadIndex)
{
var next = threadIndex - 1;
// ??ó?????????????100??
for (int i = 0; i < 100; i++)
{
var wh = _whs[next];
var sw = _sws[next];
lock (sw)
{
sw.Write(threadIndex);
}
next = (next - 1) < 0 ? 3 : next - 1;
WaitHandle.SignalAndWait(wh?? _whs[next]);  //??wh?????????????????????????????
}
}
}
???????????????????????4????????????1??2??3??4???????????????д??????4????????????????????????????????????????????????????????ó????????????????? Work ??????????д100?Ρ?
??????t1???б??е???????????????A????д??1?????? WaitHandle.SignalAndWait(wh??wh[next])??????wh???????????????д????????????????????????д??????
???????? SinalAndWait ?????μ? Thread in C# ???????? ??????? ??