线程_死锁_解锁

来源:互联网 发布:忘记数据库密码 编辑:程序博客网 时间:2024/06/06 09:45

线程死锁<12/9/2017>

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace 线程{    class Program    {        public static object o1 = new object();        public static object o2 = new object();        static void Main(string[] args)        {            Thread t1 = new Thread(                delegate ()                {                    lock (o1)                    {                        Console.WriteLine(Thread.CurrentThread.Name+"得到o1");                        lock (o2)                        {                            Console.WriteLine("得到o2");                        }                    }                    Console.WriteLine("结束");                }            );            Thread t2 = new Thread(                () =>                {                    lock (o2)                    {                        Console.WriteLine(Thread.CurrentThread.Name + "得到o2");                        lock (o1)                        {                            Console.WriteLine("得到o1");                        }                    }                    Console.WriteLine("完成");                }            );            t1.Name = "t1";            t2.Name = "t2";            t1.Start();            t2.Start();        }    }}

互相拿不到钥匙,造成死锁

线程解锁<12/9/2017>

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace 线程{    class Program    {        public static object o1 = new object();        public static object o2 = new object();        static void Main(string[] args)        {            //同步 异步            Thread t1 = new Thread(                delegate ()                {                    if (Monitor.TryEnter(o1))//试图获取对象的排他锁or互斥锁                    {                        Console.WriteLine(Thread.CurrentThread.Name + "拿到o1");                        Monitor.TryEnter(o2);                        Console.WriteLine(Thread.CurrentThread.Name + "拿到o2");                    }                }            );            Thread t2 = new Thread(                delegate ()                {                    if (Monitor.TryEnter(o2))//试图获取对象的排他锁or互斥锁                    {                        Console.WriteLine(Thread.CurrentThread.Name + "拿到o1");                        Monitor.TryEnter(o1);                        Console.WriteLine(Thread.CurrentThread.Name + "拿到o2");                    }                }            );            t1.Start();            t2.Start();        }    }}

很好的解决了普通互斥锁/排他锁所带来的弊端