我正在阅读有关 Java 线程和可重入锁的内容。 ReentrantLock 允许线程多次锁定某个资源。我的问题是,如果线程已经锁定了资源,为什么它必须这样做?这次“重入”的目的是什么?
最佳答案
假设一个类中有两个状态变量:
@GuardedBy("this")
List<String> countryList = new ArrayList<>();
@GuardedBy("this")
Map<String,String> countryCapitalMap = new ArrayList<>();
假设某个线程 A 正在访问 countryList
。这意味着它已经获得了“this”的锁。现在,由于 Java 中的锁是可重入的,这意味着线程也能够获取 countryCapitalMap
上的锁。如果获取锁是每次调用(而不是每个线程),那么一旦线程 A 获取了“this”上的锁,我就必须在它再次获取它之前释放它(以访问 countryCapitalMap
).
编辑:这是一些代码:
private synchronized insertCapital(String country, String city) {
this.countryCapitalMap.put(country, city);
}
private synchronized getRandomCountry() {
int randomInt = ...//randomly generated number
return this.countryList.get(randomInt);
}
可重入锁将使您的线程只需获取一次锁即可访问这两种方法。
关于java - 如果 Java 线程已经被该线程占用,为什么还必须重新进入该锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941719/