簡體   English   中英

為什么Java鎖實現中沒有使用synchronized關鍵字?

[英]Why is there no synchronized keyword used in Java lock implementations?

synchronized在Java中用於處理互斥體的各種事情。 但是,像Java中的ReentrantLock這樣的Lock接口的實現不使用此關鍵字。 所有代碼看起來都只是普通代碼。 那它如何處理地球上的多個線程?

我相信以下代碼片段是相關的:

Sync ReentrantLocktryAcquire方法

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 1.5(?)開始,JVM支持使用所謂的Compare-And-Swap方法進行硬件鎖定。 只需按照這些來源,直到調用它為止。

另請參閱Doug Lea的文章以獲得更好的理解: http//gee.cs.oswego.edu/dl/papers/aqs.pdf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM