首页 > 代码库 > Java_闭锁_CountDownLatch应用

Java_闭锁_CountDownLatch应用

Java_闭锁_CountDownLatch应用


闭锁是一种同步工具类,可以延迟线程的进度直到其到达终止状态。闭锁的作用相当于一扇门:在闭锁到达结束状态之前,这扇门一直是关闭的,并且没有任何线程能通过,当到达结束状态时,这扇门会打开并允许所有的线程通过。当闭锁到达结束状态后,将不会在改变状态,因此这扇门将永远保持打开状态。闭锁可以用来确定某些活动直到其他活动都完成后才继续执行,例如:

  • 确保某个计算在其需要的所有资源都被初始化之后才继续执行。二元闭锁(包括两个状态)可以用来表示“资源R已经被初始化”,而所有需要R的操作都必须在这个闭锁上等待

  • 确保某个服务在其依赖的所有其他服务都已经启动之后才启动。每个服务都有一个相关的二元闭锁。当启动服务S时,将首先在S 依赖的其他服务的闭锁上 等待,在所有依赖的服务都启动后会释放闭锁S,这样其他依赖S 的服务才能继续执行。

  • 等待直到某个操作的所有参与者都就绪再继续执行。在这种情况下,当所有玩家都准备就绪时,闭锁将到达结束状态。


CountDownLatch是一种灵活的闭锁实现,可以在上述情况中使用,他可以使一个或多个线程等待一组时间发生。闭锁状态包括一个计数器,该计数器初始化为一个正数,表示需要等待的事件数量。countDown方法递减计数器,表示有一个事件发生了,而await方法等待计数器达到零,这表示所有需要等待的事件都已经发生。如果计数器的值非零,那么await会一直阻塞直到计数器为零,或者等待中的线程中断,或者等待超时。


await()方法递增计数器

Causes the current thread to wait until the latch has counted down to zero

/**
 * Causes the current thread to wait until the latch has counted down to
 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
 *
 * <p>If the current count is zero then this method returns immediately.
 *
 * <p>If the current count is greater than zero then the current
 * thread becomes disabled for thread scheduling purposes and lies
 * dormant until one of two things happen:
 * <ul>
 * <li>The count reaches zero due to invocations of the
 * {@link #countDown} method; or
 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 * the current thread.
 * </ul>
 *
 * <p>If the current thread:
 * <ul>
 * <li>has its interrupted status set on entry to this method; or
 * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
 * </ul>
 * then {@link InterruptedException} is thrown and the current thread‘s
 * interrupted status is cleared.
 *
 * @throws InterruptedException if the current thread is interrupted
 *         while waiting
 */
public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}


countDown()方法递减计数器

Decrements the count of the latch, releasing all waiting threads if  the count reaches zero

/**
 * Decrements the count of the latch, releasing all waiting threads if
 * the count reaches zero.
 *
 * <p>If the current count is greater than zero then it is decremented.
 * If the new count is zero then all waiting threads are re-enabled for
 * thread scheduling purposes.
 *
 * <p>If the current count equals zero then nothing happens.
 */
public void countDown() {
    sync.releaseShared(1);
}


Java并发编程实战示例

在下面这个示例中,它使用两个闭锁,分别表示起始门,和 结束门。

起始门 计数器的初始值为 1,而结束门计数器 的初始值为工作线程的数量。每个工作线程首先要做的就是在启动门上等待,从而确保所有的线程都就绪后才开始执行。而每个线程要做的最后一件事就是将调用结束门的countDown 方法减一,这能使主线程高效的等待直到所有的工作线程都执行完成,因此可以统计所消耗的时间:

package com.lyx;

import java.util.concurrent.CountDownLatch;

public class TestHarness {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		Runnable task = new Runnable() {
			public void run() {
				System.out.println("hello latch............");
			}
		};
		System.out.println(timeTashs(100, task));
	}

	public static long timeTashs(int nThreads, final Runnable task)
			throws InterruptedException {
		final CountDownLatch startGate = new CountDownLatch(1);
		final CountDownLatch endGate = new CountDownLatch(nThreads);

		for (int i = 0; i < nThreads; i++) {

			Thread t = new Thread() {
				@Override
				public void run() {
					try {
						startGate.await();
						try {
							task.run();
						} finally {
							endGate.countDown();
						}
					} catch (InterruptedException e) {
						// TODO: handle exception
					}
				}
			};
			t.start();
		}

		long start = System.nanoTime();
		startGate.countDown();
		endGate.await();
		long end = System.nanoTime();
		return end - start;
	}

}


下面这个示例来自http://lbxc.iteye.com/blog/1717482

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


====================END====================


Java_闭锁_CountDownLatch应用