java--CountDownLatch用法及源码解析


countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行,
是通过一个计数器来实现的,计数器的初始化值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就相应得减1。当计数器到达0时,表示所有的线程都已完成任务

用法


@Slf4j(topic = "w.Test1")
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        new Thread(() -> {
            log.debug("t1启动");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("t1结束");
            countDownLatch.countDown();
        }, "t1").start();

        new Thread(() -> {
            log.debug("t2启动");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("t2结束");
            countDownLatch.countDown();
        }, "t2").start();

        new Thread(() -> {
            log.debug("t3启动");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("t3结束");
            countDownLatch.countDown();
        }, "t3").start();
        countDownLatch.await();
        log.debug("主线程结束");
    }
}

源码解析

public CountDownLatch(int count)

在new CountDownLatch时 我们会传入一个int类型的值来表示需要几个线程需要被等待

public CountDownLatch(int count) {
       // 判断count是否小于0 
        if (count < 0) throw new IllegalArgumentException("count < 0");
        // 调用同步器构造把count继续下传
        this.sync = new Sync(count);
    }
private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            // 发现最终是赋值给了AQS的State状态
            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;
            }
        }
    }

await

在这里插入图片描述
其调用了一个acquireSharedInterruptibly方法

public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
            // 判断线程是否被打断过
        if (Thread.interrupted())
            throw new InterruptedException();
           // 调用tryAcquireShared 下面有详解
        if (tryAcquireShared(arg) < 0)
          // 下面有方法详解
            doAcquireSharedInterruptibly(arg);
    }
 protected int tryAcquireShared(int acquires) {
 			// 判断State是否已经被减到0了 
            return (getState() == 0) ? 1 : -1;
        }
  private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
               // 获取他的前面节点
                final Node p = node.predecessor();
                // 如果p是头节点 说明是第一个等待线程
                // 因为第一个字占位节点
                if (p == head) {
                    // 再一次尝试获取锁
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                      // 如果获取到了把1当前节点设置为节点唤醒后面等待的
                        setHeadAndPropagate(node, r);
                        // 断开原来头结点
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                // 没有获取到锁到把当前节点排到等待获取锁的队列上
                if (shouldParkAfterFailedAcquire(p, node) &&
                   // 阻塞住当前线程
                    parkAndCheckInterrupt())
                    // parkAndCheckInterrupt会返回当前线程是否被打断
                    // 如果被打断就抛出异常
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

countDown

 public void countDown() {
        // 调用releaseShared调用
        sync.releaseShared(1);
    }
 public final boolean releaseShared(int arg) {
       // 调用tryReleaseShared 下面有详解
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }

tryReleaseShared

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                // 先获取State 
                int c = getState();
                if (c == 0)
                    return false;
                 // State - 1
                int nextc = c-1;
                 // 通过CAS把 把State改为nextc 相当于给State做-1操作
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }

doReleaseShared

 private void doReleaseShared() {
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
            	// 获取节点状态
                int ws = h.waitStatus;
                // 如果是-1 那么就说明他后面有等待被唤醒的线程
                if (ws == Node.SIGNAL) {
                // 把节点状态从-1 改为0 
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases				
                    // 唤醒等待的节点
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页