每个对象的锁都与 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();
}
目前, 中没有这样的类,但您可以在Mutex.javajava.util.concurrent
中找到 Mutext 实现。至于标准库,Semaphore 提供了所有这些功能等等。