synchronized在Java中用来处理互斥锁之类的事情。但是,像Java语言中的ReentrantLock这样的Lock接口实现并没有使用这个关键字。所有的代码看起来都是普通的代码。那么它如何处理地球上的多线程呢?
我相信以下代码片段是相关的:
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关键字,那么它如何保证互斥?
发布于 2013-03-24 13:08:17
从Java 1.5开始(?)JVM支持使用所谓的Compare-And-Swap方法进行硬件锁定。只需遵循源代码,直到调用此函数时为止。
另请参阅Doug Lea的论文以更好地理解:http://gee.cs.oswego.edu/dl/papers/aqs.pdf
https://stackoverflow.com/questions/15595382
复制相似问题