簡體   English   中英

使用QueudSynchronizer實現CountLatch有什么好處

[英]What is the advantage of using a QueudSynchronizer to implement CountLatch

CountLatch是一種線程控制機制,通過調用CountLatch對象上的await() )可以阻塞線程(或許多線程),當它的countDown()方法被調用了很多次時,它將釋放。

由於我熟悉使用wait()notify()的線程控制的概念,因此有一個(對我而言)明顯的CountLatch實現,如下所示:

private volatile int count; // initialised in constructor

public synchronized void countDown() {
   count--;
   if(count <= 0) {
       notifyAll();
   }
}

public synchronized void await() throws InterruptedException {
    while(count > 0) {
        wait();
    }
}

但是,Java 5提供了自己的實現java.util.concurrent.CountLatch ,它使用從AbstractQueuedSynchronizer擴展的內部類。

private static final class Sync extends AbstractQueuedSynchronizer {
    Sync(int count) {
        setState(count);
    }

    int getCount() {
        return getState();
    }

    protected int tryAcquireShared(int acquires) {
        return (getState() == 0) ? 1 : -1;
    }

    protected boolean tryReleaseShared(int releases) {
        // Decrement count; signal when transition to zero
        for (;;) {
            int c = getState();
            if (c == 0)
                return false;
            int nextc = c-1;
            if (compareAndSetState(c, nextc))
                return nextc == 0;
            }
        }
    }

Java 5 CountLatch本質上是這個Sync對象的包裝器:

  • countDown()調用sync.releaseShared(1)
  • await()調用sync.acquireSharedInterruptibly(1)

這種更復雜的方法有什么優勢?

您提出的方法與JDK之間的主要區別在於您正在使用鎖,而AbstractQueuedSynchronizer是無鎖的,並且在內部使用Compare-And-Swap,這在中等爭用下提供了更好的性能。

暫無
暫無

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

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