• 多线程07-Monitor.TryEnter


        class Program
        {
            static void Main()
            {
                object lock1 = new object();
                object lock2 = new object();
                new Thread(() => LockTooMuch(lock1, lock2)).Start();
                lock (lock2)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("Monitor.TryEnter allows not to get stuck,returning false after a specified timeout is elapsed");
                    if (Monitor.TryEnter(lock1, TimeSpan.FromSeconds(5)))
                    {
                        Console.WriteLine("Acquired a protected resourece success");
                    }
                    else
                    {
                        Console.WriteLine("time out to get a resource");
                    }
                }
                new Thread(() => LockTooMuch(lock1, lock2)).Start();

                lock (lock2)
                {
                    Console.WriteLine("this will be a deadlock");
                    Thread.Sleep(1000);
                    lock (lock1)
                    {
                        Console.WriteLine("Acquired a protected resourece success");
                    }
                }


            }
            static void LockTooMuch(object lock1, object lock2)
            {
                lock (lock1)
                {
                    Thread.Sleep(1000);
                    lock (lock2)
                    {

                    }
                }
            }

        }
  • 相关阅读:
    linux安装jdk(二)
    Java实现进程调度算法(一) FCFS(先来先服务)
    用Java Swing实现Freecell(空当接龙)
    windows主机开启MySQL慢查询日志
    CentOS LNMP 服务器安装配置详解
    shopex 网店系统 v4.8.5 安装图文教
    mysqldumpslow和mysqlsla分析mysql慢查询日志
    window下nginx配置
    PHP开发编码规范
    IIS+PHP+MySQL+Zend Guard Loader(ZendOptimizer)+phpMyAdmin环境配置图解(转)
  • 原文地址:https://www.cnblogs.com/shidengyun/p/5600942.html
Copyright © 2020-2023  润新知