C#模拟死锁问题

    /// <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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值