class MyBarrier
{
public delegate void callback(int number );
private readonly int thread_count;
private readonly callback call;
public int currentNumeric { get; set; }
private object oLock = new object();
private int count = 0;
public MyBarrier(int thread_count, callback call)
{
this.thread_count = thread_count;
this.call = call;
}
public void SignalAndWait()
{
lock (this.oLock)
{
this.count++;
if (this.count % this.thread_count == 0)
{
this.call((this.count / this.thread_count));
Monitor.PulseAll(this.oLock);
}
else
{
Monitor.Wait(this.oLock);
}
}
}
}
以下是Main函数:
class Program
{
static MyBarrier _barrier = new MyBarrier(3, delegate(int b)
{
Console.WriteLine("当前是第"+ b+"次碰面");
Thread.Sleep(TimeSpan.FromSeconds(2));
});
static void Main(string[] args)
{
new Thread(() => PlayMusic("sam", "程序员", 3)).Start();
new Thread(() => PlayMusic("jim", "程序员", 4)).Start();
new Thread(() => PlayMusic("tom", "程序员", 5)).Start();
Console.ReadKey();
}
static void PlayMusic(string name, string message, int seconds)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("----------------------------");
Console.WriteLine(name + " " + message);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine(name + " " + message);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
_barrier.SignalAndWait();
}
}
}