使用QueudSynchronizer实现CountLatch有什么好处

sli*_*lim 6 java concurrency multithreading

CountLatch是一种线程控制机制,通过调用await()CountLatch对象可以阻塞线程(或多个线程),当对象的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Java 5 CountLatch本质上是这个Sync对象的包装器:

  • countDown() 电话 sync.releaseShared(1)
  • await() 电话 sync.acquireSharedInterruptibly(1)

这种更复杂的方法有什么优势?

ass*_*ias 5

您提出的方法与JDK之间的主要区别在于您使用的AbstractQueuedSynchronizer是锁定而无锁定并且在内部使用了比较和交换,这在中等争用下提供了更好的性能.