日期:2014-05-19  浏览次数:20872 次

懂lock的帮帮我,很简单的


using   System;
using   System.Threading;

class   salary
{
private   static   int   count=100;
private   object   abcde=new   object();

public   int   Count
{
get{return   count;}
}


public   void   RunThread1()
{
lock(abcde)
{
count+=5;
}
}
public   void   RunThread2()
{
lock(abcde)
{
count-=2;
}
}
public   static   void   Main(string[]   args)
{
salary   s=new   salary();
Thread   thread1=new   Thread(new   ThreadStart(s.RunThread1));
Thread   thread2=new   Thread(new   ThreadStart(s.RunThread2));
thread1.Start();
Console.WriteLine( "Now   Salary   is:   "+s.Count);
thread2.Start();
Console.WriteLine( "Now   Salary   is:   "+s.Count);

}
}


----------------------------

开始count是=100
执行线程1   是要让它+5   =105
执行线程2   是要让它-2   =103

但为什么我得到的结果会是
Now   Salary   is:   100
Now   Salary   is:   100

为什么不是
Now   Salary   is:   105
Now   Salary   is:   103          



------解决方案--------------------
不会把,我执行你的代码是
Now Salary is: 105
Now Salary is: 103

...
------解决方案--------------------
因为你是线程执行的,所以下面2句代码并不是按先后顺序执行的。
thread1.Start();
Console.WriteLine( "Now Salary is: "+s.Count);
就是thread1开始了,跟着就执行Console.WriteLine( "Now Salary is: "+s.Count);,

但thread1线程中的count+=5代码可能还不执行,
Console.WriteLine( "Now Salary is: "+s.Count);和count+=5这2句代码是没有执行先后关系的
------解决方案--------------------
你单步调试的看下,就知道程序是怎么在走了。。
------解决方案--------------------
楼主可以设置2个断点在
Console.WriteLine( "Now Salary is: "+s.Count);
count+=5

看看是不是先执行了Console.WriteLine( "Now Salary is: "+s.Count);
------解决方案--------------------
lock的作用只是为了避免多线程冲突,与线程的执行顺序无关,当然并发冲突的机会非常小的.