[转]C#模拟死锁问题

来源:互联网 发布:nginx asp.net mvc 编辑:程序博客网 时间:2024/06/06 21:39

/// <summary>
    /// 模拟学生作笔记,假设一个学生只有同时拥有笔记本和笔才能学习,
    /// 这里模拟2个学生,但只有1个笔记本和一只笔
    /// 如果想进行学习,需同时获得笔记本和笔,当A同学获得笔记本时,
    /// B也已获得笔,此时,A试图获得B的笔,而B试图获得A的笔记本,
    /// 此时便发生死锁
    /// </summary>

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ThreadTest
{
    
/// <summary>
    
/// 模拟学生作笔记,假设一个学生只有同时拥有笔记本和笔才能学习,
    
/// 这里模拟2个学生,但只有1个笔记本和一只笔
    
/// 如果想进行学习,需同时获得笔记本和笔,当A同学获得笔记本时, 
    
/// B也已获得笔,此时,A试图获得B的笔,而B试图获得A的笔记本,
    
/// 此时便发生死锁
    
/// </summary>
    class Program
    {
        
static void Main(string[] args)        
        {
            Tool t1 
= new Tool("Book");//笔记本
            Tool t2 = new Tool("Pen");//
            Student a = new Student("A",t1,t2);//A学生
            Student b = new Student("B",t2,t1);//B学生
            Thread ta = new Thread(new ThreadStart(a.Run));
            Thread tb 
= new Thread(new ThreadStart(b.Run));
            ta.Start();
            tb.Start();
        }
    }
    
public class Tool
    {
       
public  string Name;
        
public Tool(string Name)
        {
            
this.Name = Name;
        }
    }
    
class Student
    {
        
private string Name;
        
private Tool Tool1;
        
private Tool Tool2;
         
        
public Student(string Name,Tool tool1,Tool tool2)
        {           
           
this.Name = Name;
           
this.Tool1 = tool1;
           
this.Tool2 = tool2;
        }
        
public void Run()
        {
            
while(true)
                Study();
        }

        
private void Study()
        {
            
lock (Tool1)//得到并锁住工具1
            {
                Console.WriteLine(
"{0} get  {1}", Name,Tool1.Name);
                
lock (Tool2)//得到并锁住工具2
                {
                    Console.WriteLine(
"{0} get  {1}", Name, Tool2.Name);                    
                    Console.WriteLine(
"{0} Will Study", Name);//得到工具并学习
                    Console.WriteLine("{0} Dorp  {1}", Name, Tool1.Name);  //释放工具1
                }
                Console.WriteLine(
"{0} Dorp  {1}", Name, Tool2.Name);   //释放工具2
                
            }
             
        }
    }
}

 

运行结果:

--------------------------------

A get  Book
B get  Pen

-----------