synchronized
在 Java 中用于处理互斥锁之类的事情。然而Lock
接口(interface)的实现如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
extends 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 1.5(?) 开始,JVM 支持使用所谓的 Compare-And-Swap 进行硬件锁定。方法。只需关注来源,直到调用它为止。
另请参阅 Doug Lea 的论文以更好地理解:http://gee.cs.oswego.edu/dl/papers/aqs.pdf
关于java - 为什么在 Java 锁实现中没有使用 synchronized 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15595382/