MOnitor线程同步

    技术2025-08-23  29

    class Program { static int n = 0; static object mk = new object(); static void foo1() { for (int i = 0; i < 1000000000; i++) // 10 亿 { Monitor.Enter(mk); int a = n; n = a + 1; Monitor.Exit(mk); } Console.WriteLine("foo1() complete n = {0}", n); } static void foo2() { for (int j = 0; j < 1000000000; j++) // 10 亿 { Monitor.Enter(mk); int a = n; n = a + 1; Monitor.Exit(mk); } Console.WriteLine("foo2() complete n = {0}", n); } static void Main(string[] args) { new Thread(foo1).Start(); new Thread(foo2).Start(); } }
    Processed: 0.010, SQL: 9