为什么下面这段代码不会导致死锁?
根据我对多线程编程的有限理解,当getBar1()
被调用时,sharedBuffer
将被“锁定”,因此,当方法尝试调用getBar2()
时,线程将不得不等待sharedBuffer
(它自己持有!)。换句话说,直到has (和 release )getBar2()
才能返回。但另一方面,也不能返回,因为它正在等待返回。getBar1()
sharedBuffer
getBar1()
getBar2()
==> 死锁。(但实际上并非如此,这就是我感到困惑的原因)
...
Foo sharedBuffer = new Foo();
Bar1 getBar1()
{
Bar1 bar1;
synchronized (sharedBuffer)
{
bar1 = sharedBuffer.getBar1();
if (bar1 == null)
bar1 = new Bar1(sharedBuffer, getBat2());
sharedBuffer.setBar1(bar1);
}
return bar1;
}
Bar2 getBar2()
{
Bar2 bar2;
synchronized (sharedBuffer)
{
bar2 = sharedBuffer.getBar2();
if (bar2 == null)
bar2 = new Bar2();
}
return bar2;
}
...