java 闭锁

闭锁1

定义: 在闭锁到达结束状态之前,这扇们一直是关闭的,并且没有线程能通过,当到达结束状态时,这扇门会打开并允许所有的线程通过。

 

举例:计算n个人比赛跑步。

比赛跑步要保证n个人是同步听见枪响。

 

    public long runSample(int n, final Runnable runSport) throws InterruptedException {
        final CountDownLatch gun = new CountDownLatch(1);
        final CountDownLatch end = new CountDownLatch(n);
        
        for (int i = 0; i < n; i++){
            Thread t = new Thread() {
                public void run(){
                    try{
                    gun.await();//等待开枪
                    try{
                    runSport.run();
                    }finally{
                        end.countDown();
                    }
                    }catch( InterruptedException e){
                        Thread.currentThread().interrupt();
                    }
                }
            };
            t.start();
        }
        long startTime = System.nanoTime();
        gun.countDown();//开枪
        end.await();
        long endTime = System.nanoTime();
        return endTime - startTime;
    }

你可能感兴趣的:(java)