最近在使用Interlock时,出现读值错误,所以写了一个demo,有大神帮忙看看有什么问题。
namespace ThreadDemo
{
class Tester
{
private int counter = 0;
static void Main(string[] args)
{
//make an instance of this class
Tester t = new Tester();
//run outside static Main
t.DoTest();
Console.ReadKey();
}
private void DoTest()
{
Thread t1 = new Thread(new ThreadStart(Incrementer));
t1.IsBackground = true;
t1.Name = "ThreadOne";
t1.Start();
Console.WriteLine("Started thread {0}",t1.Name);
Thread t2 = new Thread(new ThreadStart(Incrementer));
t2.IsBackground = true;
t2.Name = "ThreadTwo";
t2.Start();
Console.WriteLine("Started thread {0}", t2.Name);
t1.Join();
t2.Join();
//等待所有的线程都结束
Console.WriteLine("All my threads are done.");
}
//线程调用的函数
private void Incrementer()
{
//Console.WriteLine("Incrementer:{0}",counter);
try
{
while (counter < 10)
{
//使用互锁
Interlocked.Increment(ref counter);
//线程挂起
Thread.Sleep(1);
//显示结果
Console.WriteLine("Thread {0}.Incrementer:{1}",Thread.CurrentThread.Name,counter);
}
}
catch(ThreadInterruptedException)
{
Console.WriteLine("Thread {0} Interlocked!Cleaning up ...",Thread.CurrentThread.Name);
}
finally
{
Console.WriteLine("Thread {0} Exiting.",Thread.CurrentThread.Name);
}
}
}
}
结果显示如下图:
我已经使用Interlocked进行了锁定,为什么线程2在线程1没有结束的时候会改变变量的值,求大神帮忙看看。