zoukankan      html  css  js  c++  java
  • C# 死锁

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    namespace Demon
    {
        class Program
        {
            private static object obj1 = new object();
            private static object obj2 = new object();
            private static int count = 0;
            static void Main()
            {
                Thread T1 = new Thread(Thread1);
                Thread T2 = new Thread(Thread2);
                T1.Start();
                T2.Start();
                while (true)
                {
                  
                    Console.WriteLine("dead lock! count:{0}", count);
                }
            }
            private static void Thread1()
            {
                while (true)
                {
                    Monitor.Enter(obj1);   //先锁obj2,参数为对象,如果是值类型则需要装箱
                    Monitor.Enter(obj2);//再锁obj1
                    count++;
                    Monitor.Exit(obj1);  //释放锁不存在先后关系
                    Monitor.Exit(obj2);
                }
            }
            private static void Thread2()
            {
                while (true)
                {
                    Monitor.Enter(obj1);  //先锁obj1
                    Monitor.Enter(obj2);
                    count++;
                    Monitor.Exit(obj1);
                    Monitor.Exit(obj2);
                }
            }
        }
    }

  • 相关阅读:
    Matlab 基础
    C# 基础
    Linux Shell
    【Luogu3381】【模板】缩点
    KMP学习笔记
    品味题目的味道
    【NOI2015】【BZOJ4196】软件包管理器
    宝藏
    状态压缩动态规划
    第一篇随笔
  • 原文地址:https://www.cnblogs.com/zztong/p/6695203.html
Copyright © 2011-2022 走看看