每个对象的锁与Mutex / Semaphore设计几乎没有什么不同。例如,没有办法通过释放前一个节点的锁并捕获下一个的锁来正确实现遍历链接的节点。但是使用互斥锁很容易实现:
Node p = getHead();
if (p == null || x == null) return false;
p.lock.acquire(); // Prime loop by acquiring first lock.
// If above acquire fails due to interrupt, the method will
// throw InterruptedException now, so there is no need for
// further cleanup.
for (;;) {
Node nextp = null;
boolean found;
try {
found = x.equals(p.item);
if (!found) {
nextp = p.next;
if (nextp != null) {
try { // Acquire next lock
// while still holding current
nextp.lock.acquire();
}
catch (InterruptedException ie) {
throw ie; // Note that finally clause will
// execute before the throw
}
}
}
}finally { // release old lock regardless of outcome
p.lock.release();
}
当前没有此类java.util.concurrent
,但是您可以在Mutex.java中找到Mutext实现。至于标准库,Semaphore提供了所有这些功能以及更多其他功能。