多线程资源共享问题案例:
--原因不解释,学习案例。
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 ;
public int Count
{
get { return count; }
set { count = value; }
}
public void Increment()
{
count++;
}
public void Decrement()
{
count--;
}
}
class Program
{
static void CallCounter( CountTest c)
{
for (int i = 0; i < 1000000; i++)
{
c.Increment();
c.Decrement();
}
}
static void Main(string[] args)
{
var tc = new CountTest();
var t1 = new Thread(() => CallCounter(tc));
var t2 = new Thread(() => CallCounter(tc));
var t3 = new Thread(() => CallCounter(tc));
var t4 = new Thread(() => CallCounter(tc));
t1.Start();
t2.Start();
t3.Start();
t4.Start();
t1.Join();
t2.Join();
t3.Join();
t4.Join();
Console.WriteLine(" {0} ",tc.Count);
Console.Read();
}
}
}
每次运行结果不确定: