遇到的一段面试题:问下面的类运行 Test的时候是否会引起死锁。
publicclass MyClass
{
publicvoid Test(int num)
{
if (num > 10)
{
lock (this)
{
num--;
Test(num);
}
}
}
}
当一个互斥锁已被占用时,在同一线程中执行的代码仍可以获取和释放该锁。但是,在其他线程中执行的代码在该锁被释放前是无法获得它的。
class Program
{
static void Main(string[] args)
{
Program prg = new Program();
Thread t1 = new Thread(delegate(){prg.Test(20); });
t1.Name = "T1";
Thread t2 = new Thread(delegate() { prg.Test(20); });
t2.Name = "T2";
t1.Start();
t2.Start();
Console.ReadLine();
}
void Test(int num)
{
if (num > 10)
{
lock (this)
{
Thread.Sleep(1000);
Console.WriteLine("current thread:{0},num is:{1}",Thread.CurrentThread.Name,num);
num--;
Test(num);
}
}
}
}
可以说这个地方是不会发生死锁的,因为在递归的调用过程中,num是一个值类型,在递归的各层中都是独立的,是不会发生死锁的
死锁是要发生资源争夺得,这里会吗??传值的时候指向的是不同内存资源吧,怎么争夺法呢