C#之lock的使用及说明

  using System;

  using System.Collections.Generic;

  using System.Linq;

  using System.Text;

  using System.Threading;

  using System.Threading.Tasks;

  namespace ConsoleApp2

  {

  class Program

  {

  static int a = 0;

  static int b = 0;

  private static object o = new object();

  static void Main(string[] args)

  {

  //A();

  //B();

  Thread t1 = new Thread(A);

  Thread t2 = new Thread(B);

  t1.Start();

  t2.Start();

  Thread t3 = new Thread(C);

  t3.Start();

  Console.ReadLine();

  }

  private static void A()

  {

  //lock (o)

  Monitor.Enter(o);

  a = a + 2;

  Console.WriteLine("我是A方法,a=" + a);

  Thread.Sleep(5000);//暂停5秒

  b = b + 2;

  Console.WriteLine("我是A方法,b=" + b);

  Monitor.Exit(o);

  }

  private static void B()

  {

  //lock (o)

  Monitor.Enter(o);

  b++;

  Console.WriteLine("我是B方法,b=" + b);

  Thread.Sleep(1000); //暂停1秒

  a++;

  Console.WriteLine("我是B方法,a=" + a);

  Monitor.Exit(o);

  }

  private static void C()

  {

  Console.WriteLine("我是C方法,随机出现");

  }

  }

  }