论坛首页 编程语言技术论坛

CountDownLatch 理解

浏览 2032 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-11-26  
Latch 在英文中是门阀的意思。也就是控制门的开关的关键。
所以,Latch在并发中,就是控制线程访问的。《JCP》中列举了几点用途:
1,等待资源初始化。
2,等待依赖服务启动。
3,等待队友加入活动。

具体的Latch有 CountDownLatch,如果只是说功能什么的,还是比较疑惑。
CountDownLatch 的功能就是初始化一个值,每次调用countDown方法时这个值就减 1
注意初始化的值应该是正的,否則Throws:
IllegalArgumentException - if count is negative),而 await方法就是阻塞线程,直到这个值减为0
这个有什么用呢?

书上给出的例子很好,就是计算多个线程运行消耗的时间。这里我们要注意,如何判断开始和结束呢? 因为多线程中,很可能有的线程启动快,你得选取一个计时点。如果从添加任务开始,那么明显不准缺,添加本身的时间也算上了,所以必须有个时间点,在此之前所有线程都必须等待。于是CountDownLatch变成了发令枪,一声枪响,所有线程就可以狂奔了。
同样结束也是要等待最后一个线程完成。所以也可以用CountDownLatch作为计数员。
这下,我把这个例子变成跑步比赛了。书中的例子好比记录比赛的时间。
运动员就是任务,跑步就是他们的任务,每条跑道就是一个线程。第一个阀门就是发令枪,
在此之前运动员都只是在跑道上等着。第二个阀门则是控制裁判员的,必须等到最后一个运动员跑完才计时结束。
接下来直接看代码:
import java.util.concurrent.CountDownLatch;

public class CompetitionTime {
    public long getCompetitionTime( int nAthlete, final Runnable Athlete ) 
         throws InterruptedException {
        // the starting gun just shot once.
        final CountDownLatch startingGun = new CountDownLatch( 1 );
        // every athlete should complete the competition.
        final CountDownLatch endCompetition = new CountDownLatch( nAthlete );

        for ( int i = 0; i < nAthlete; i++ ) {
            Thread t = new Thread() {
                public void run() {
                    try {
                        //before running, athlete must wait for shot of the starting gun 
                        startingGun.await();
                        try {
                            Athlete.run();
                        }
                        finally {
                            //when he finishes his competition,let the referee know
                            endCompetition.countDown();
                        }
                    }
                    catch ( InterruptedException ignored ) {

                    }
                }
            } ;
            t.start();
          //now the thread must wait for the shot of the starting gun
        }
            
            //the following two can exchange the order. 
            long start = System.nanoTime();
            startingGun.countDown();
            //then we just wait for the last athlete done.
            // the main thread is blocking.
            endCompetition.await();
            // that means all athlete finish their competition.
            long end = System.nanoTime();
            return end - start;
        }
    }

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics