我有一個很難理解ReentrantLock.lock()ReentrantLock.lock()不會阻止其他線程
我有下面的類行爲
import java.util.concurrent.locks.*;
class BlockingClass {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void a() {
lock.lock();
System.out.println("called in method a(): lock()");
try {
System.out.println("called in method a(): await()");
condition.await();
}
catch (InterruptedException e) {}
finally {
lock.unlock();
System.out.println("called in method a(): unlock() ");
}
}
public void b() {
lock.lock();
System.out.println("called in method b(): lock()");
System.out.println("called in method b(): signalAll()");
condition.signalAll();
lock.unlock();
System.out.println("called in method b(): unlock() ");
}
}
我與運行以下測試:
class BlockingClassTest {
public static void main(String[] args) throws InterruptedException {
final BlockingClass blockingClass = new BlockingClass();
new Thread() {
public void run() {
System.out.println("Thread1 calling a()");
blockingClass.a();
}
}.start();
Thread.sleep(1000);
new Thread() {
public void run() {
System.out.println("Thread2 calling b()");
blockingClass.b();
}
}.start();
}
}
我本來預計會出現死鎖。一旦a()方法調用lock.lock(),我期望任何調用b()方法的人都必須在b的lock.lock()處等待,直到調用a()的線程調用lock.unlock()。但是由於a()正在等待b()調用condition.signalAll(),所以這兩種方法都應該永遠保持阻塞狀態。
相反,這是我的輸出在控制檯中看到:
Thread1 calling a()
called in method a(): lock()
called in method a(): await()
Thread2 calling b()
called in method b(): lock()
called in method b(): signalAll()
called in method a(): unlock()
called in method b(): unlock()
什麼我誤解有關正確使用和鎖定功能()和unlock()?
謝謝,@ortang和傑森C爲您的偉大和快速的答案。我僅僅因爲它的完整性和有用的文檔而接受這個。 – Student