using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication6
{
class CountTest
{
private int count = 0;
public int Count
{
get { return count; }
set { count = value; }
}
public void Increment()
{
count++;
}
public void Decrement()
{
count--;
}
}
class Program
{
private static AutoResetEvent Event_1 = new AutoResetEvent(true);
static void TestCounter(CountTest c)
{
Console.WriteLine("{0} 请求互斥锁", Thread.CurrentThread.Name);
Event_1.WaitOne();
Console.WriteLine("\n{0} 已获得互斥锁", Thread.CurrentThread.Name);
for (int i = 0; i < 1000000; i++)
{
c.Increment();
c.Decrement();
}
Event_1.Set();
Console.WriteLine("{0} 已获释放斥锁", Thread.CurrentThread.Name);
Thread.Sleep(500);
}
static void Main(string[] args)
{
var tc = new CountTest();
for (int i = 1; i <= 4; i++)
{
Thread MyThread = new Thread(() => TestCounter(tc));
MyThread.Name = string.Format("Thread_{0}",i);
MyThread.Start();
MyThread.Join();
}
Console.WriteLine("\n计算结果为:{0} ", tc.Count);
Console.Read();
}
}
}