欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

并发工具CountDownLatch源码分析

程序员文章站 2022-12-16 12:38:11
CountDownLatch的作用类似于Thread.join()方法,但比join()更加灵活。它可以等待多个线程(取决于实例化时声明的数量)都达到预期状态或者完成工作以后,通知其他正在等待的线程继续执行。简单的说,Thread.join()是等待具体的一个线程执行完毕,CountDownLatc ......

  countdownlatch的作用类似于thread.join()方法,但比join()更加灵活。它可以等待多个线程(取决于实例化时声明的数量)都达到预期状态或者完成工作以后,通知其他正在等待的线程继续执行。简单的说,thread.join()是等待具体的一个线程执行完毕,countdownlatch等待多个线程。

  如果需要统计4个文件中的内容行数,可以用4个线程分别执行,然后用一个线程等待统计结果,最后执行数据汇总。这样场景就适合使用countdownlatch。

  本篇从countdownlatch的源码分析它的原理机制。再给出一个简单的使用案例。

  

  首先认识一下countdownlatch中的内部类:

private static final class sync extends abstractqueuedsynchronizer {
        private static final long serialversionuid = 4982264981922014374l;

        sync(int count) {
            setstate(count);   // 更新aqs中的state
        }

        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;
            }
        }
    }

  其实countdownlatch的机制和reentrantlock有点像,都是利用aqs(abstractqueuedsynchronizer)来实现的。countdownlatch的内部类sync继承aqs,重写了tryacquireshared()方法和tryreleaseshared()方法。这里的重点是countdownlatch的构造函数需要传入一个int值count,就是等待的线程数。这个count被sync用来直接更新为aqs中的state。

  

1、await()等待方法

//countdownlatch
public void await() throws interruptedexception { sync.acquiresharedinterruptibly(1); } //aqs public final void acquiresharedinterruptibly(int arg) throws interruptedexception { if (thread.interrupted()) throw new interruptedexception(); if (tryacquireshared(arg) < 0) // 1 doacquiresharedinterruptibly(arg); // 2   } //sync protected int tryacquireshared(int acquires) { return (getstate() == 0) ? 1 : -1; } //aqs private void doacquiresharedinterruptibly(int arg) throws interruptedexception { final node node = addwaiter(node.shared); boolean failed = true; try { for (;;) { final node p = node.predecessor(); if (p == head) { int r = tryacquireshared(arg); if (r >= 0) { setheadandpropagate(node, r); p.next = null; // help gc failed = false; return; } } if (shouldparkafterfailedacquire(p, node) && parkandcheckinterrupt()) throw new interruptedexception(); } } finally { if (failed) cancelacquire(node); } }
  1. 调用aqs中的tryacquireshared()方法时,sync重写了tryacquireshared()方法,获取state,判断state是否为0。
  2. 如果不为0,调用doacquiresharedinterruptibly()方法,将线程加入队列,挂起线程。

2、countdown()

public void countdown() {
        sync.releaseshared(1);
    }
//aqs public final boolean releaseshared(int arg) { if (tryreleaseshared(arg)) { doreleaseshared(); return true; } return false; }
//sync 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; } }

  重点也是在于sync重写的tryreleaseshared()方法。利用cas算法将state减1。如果state减到0,说明所有工作线程都执行完毕,那么就唤醒等待队列中的线程。

使用示例:

public class countdownlatchtest {
    private static countdownlatch countdownlatch = new countdownlatch(3);
    private static threadpoolexecutor threadpool = new threadpoolexecutor(5, 5,
            0l, timeunit.milliseconds,
            new linkedblockingqueue<runnable>(10));
    
    public static void main(string[] args) {
        //等待线程
        for (int i = 0; i < 2; i++) {
            string threadname = "等待线程 " + i;
            threadpool.execute(new runnable() {
                
                @override
                public void run() {
                    try {
                        system.out.println(threadname + " 正在等待...");
                        //等待
                        countdownlatch.await();
                        system.out.println(threadname + " 结束等待...");
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                }
            });
        }
        //工作线程
        for (int i = 2; i < 5; i++) {
            string threadname = "工作线程 " + i;
            threadpool.execute(new runnable() {
                
                @override
                public void run() {
                    try {
                        system.out.println(threadname + " 进入...");
                        //沉睡1秒
                        timeunit.milliseconds.sleep(1000);
                        system.out.println(threadname + " 完成...");
                        //通知
                        countdownlatch.countdown();
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                }
            });
        }
        
        threadpool.shutdown();
    }
}

 

  执行结果为:

等待线程 1 正在等待...
等待线程 0 正在等待...
工作线程 2 进入...
工作线程 3 进入...
工作线程 4 进入...
工作线程 3 完成...
工作线程 2 完成...
工作线程 4 完成...
等待线程 0 结束等待...
等待线程 1 结束等待...

  从结果也能看到,等待线程先执行,调用countdownlatch.await()方法开始等待。每个工作线程工作完成以后,都调用countdownlatch.countdown()方法,告知自己的任务完成。countdownlatch初始参数为3,所以3个工作线程都告知自己结束以后,等待线程才开始工作。