using System;
using System.Threading;
class test
{
    private static int i=0;
    public static void Add()
    {
        //A:start
        int a=i;
        Thread.Sleep(1000);
        int b=i++;
        Console.WriteLine("b-a={0}",b-a);
        //E:end
    }
    public static void Main()
    {
        Thread[] th=new Thread[1000];
        for(int j=0; j<1000; j++)
        {
            th[i]=new Thread(new ThreadStart(Add));
            th[i].Start();
            Thread.Sleep(167);
        }
    }}
/* 实际运行这个程序,其输出结果如下:
b-a=0
b-a=1
b-a=2
b-a=3
b-a=4
b-a=5
b-a=5
b-a=5
b-a=5
...一直"b-a=5"下去...
...我应当如何修改Add()函数才能使得输出结果始终为下面的样子呢?
b-a=1
b-a=1
b-a=1
b-a=1
...
b-a=1也就是说在A:start和B:end处插入什么样的代码才能将"i"从A开始锁定,到B处释放?
在锁定期间,其他线程不得访问"i",直到释放为止。
这个有些类似于数据库中的事务处理或者表/行锁定,C#中能够做到吗?
请各位高人指点!
*/

解决方案 »

  1.   

    Lock
    Monitor
     方法大大的有
      

  2.   


        public static void Add()
        {
          lock(i)
          {
            int a=i;
            Thread.Sleep(1000);
            int b=i++;
            Console.WriteLine("b-a={0}",b-a);
           }
        }
    /*我测试了一下,这样改写是不行的,说“int不是lock语句要求的应用类型”,怎么办啊?*/
      

  3.   

    简单办法:
            //A:start
            int _i = i;
            int a=i;
            Thread.Sleep(1000);
            int b=i++;
            Console.WriteLine("b-a={0}",b-a);
            i = _i;
            //E:end
      

  4.   

    如果test只有一个static i
    也可以:lock ( typeof( test ) )
      

  5.   

    我只想锁定 i 
    如果用lock(typeof(test))岂不是将整个test都锁住了?
    这样会影响到其他的成员吧?
      

  6.   

    using System;
    using System.Threading;namespace Test
    {
    /// <summary>
    /// Class1 的摘要说明。
    /// </summary>
    class Class1
    {
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    //
    // TODO: 在此处添加代码以启动应用程序
    //
    Thread[] th=new Thread[1000];
    for(int j=0; j<1000; j++)
    {
    ThreadStart ts=new ThreadStart(Add);
    th[j]=new Thread(ts);
    th[j].Priority=ThreadPriority.Highest;
    th[j].Start();
    //Thread.Sleep(1670);
    }
    Console.ReadLine();
    }
    private static int i=0;
    public static void Add()
    {
    //A:start
    int a=i;
    //Thread.Sleep(1000);
    int b=++i;
    Console.WriteLine("b-a={0}和a={1}和b={2}",b-a,a,b);

    //E:end
    }
    }
    }