【发布时间】:2013-03-24 05:03:16
【问题描述】:
synchronized 在 Java 中用于处理互斥锁之类的事情。然而,Lock 接口(如 Java 中的 ReentrantLock)的实现不使用此关键字。所有代码看起来都只是普通代码。那它到底是怎么处理多线程的呢?
我相信以下代码片段是相关的:
ReentrantLock的Sync中的tryAcquire方法
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
Sync 扩展 AbstractQueuedSynchronizer 和相关代码:
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
所以似乎没有使用synchronized 关键字,那么它如何保证互斥锁?
【问题讨论】:
标签: java multithreading synchronized reentrantlock