2 回答
TA贡献1862条经验 获得超6个赞
我建议您lock为每个Warehouse对象引入一个变量以及一个唯一的整数。您可以使用 anAtomicInteger来确保每个创建的仓库都有其唯一编号
public class Warehouse {
private static final AtomicInteger numberProvider = new AtomicInteger(0);
private final int number;
private final Lock lock = new ReentrantLock();
// ...
public Warehouse(...) {
this.number = numberProvider.incrementAndGet();
...
}
// ... (getter for number and lock and other methods)
}
这样您就可以始终以“正确”的顺序锁定两个仓库(例如,先锁定较低的数字,然后锁定较高的数字;向后解锁)。这将保证您不会遇到死锁。
public void moveStock(Warehouse from, Warehouse to, int nof) {
List<Lock> locks = Stream.of(from, to)
.sorted(Comparator.comparingInt(Warehouse::getNumber))
.map(Warehouse::getLock)
.collect(Collectors.toList());
for(int i=0;i<locks.size();++i) {
locks.get(i).lock();
}
try {
from.substractStock(nof);
to.addStock(nof);
} finally {
for(int i=locks.size()-1;i>=0;i--) {
locks.get(i).unlock();
}
}
}
添加回答
举报