我想知道使用ReentrantLock是否是我的问题的解决方案;我正在尝试“锁定”(防止其他线程访问/使用它)一个对象,直到某个操作完成,然后解锁它以便其他线程可以访问它。我想使用sun的不安全的#monitorEnter/exit,但这可能会导致死锁。
想象一下下面的情况:
public void doSomething() {
Object object = someObject;
// Object should be locked until operation is complete.
doSomethingElse(object);
// Object should now be unlocked so other threads can use/access it.
}
public void doSomethingElse(Object object) {
// Something happens to the object here
}这就是解决方案吗?
ReentrantLock reentrantLock = new ReentrantLock();
public void doSomething() {
Object object = someObject;
// Object should be locked until operation is complete.
reentrantLock.lock();
doSomethingElse(object);
reentrantLock.unlock();
// Unlock object for other threads after complete.
}
public void doSomethingElse(Object object) {
// Something happens to the object here
}提前谢谢。
https://stackoverflow.com/questions/51370537
复制相似问题