Use of countdownlatch in Java concurrency

In Java concurrency, controlling the access of shared variables is very important. Sometimes we also want to control the execution order of concurrent threads, such as waiting for all threads to execute before executing another thread, or waiting for all threads to be ready before starting the execution of all threads.

At this time, we can use countdownlatch.

Simply put, countdownlatch stores a counter in queuedsynchronizer. When the countdown () method is called, the counter is decremented by one. Await () is then called to wait for the counter to return to zero.


private static final class Sync extends AbstractQueuedSynchronizer {
    ...
}

private final Sync sync;

    public void countDown() {
        sync.releaseShared(1);
    }
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

Here are two examples:

The main thread waits for all the child threads to finish before running

Wait until all threads are ready to execute together

Stop the await of countdownlatch

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>