使用CountDownLatch協調子線程

從JDK 1.5以後,在java.util.concurrent包下引入了好多的處理多線程的工具類,本文將介紹CountDownLatch工具類,並採用這個工具類給出一個實例。java

 CountDownLatch工具類介紹

CountDownLatch描述

CountDownLatch是一個同步工具類,它容許一個或多個線程處於等待狀態直到在其它線程中運行的一組操做完成爲止。CountDownLatch用一個給定的計數來實現初始化。Await方法會一直處於阻塞狀態,直到countDown方法調用而使當前計數達到零。當計數爲零以後,全部處於等待的線程將被釋放,await的任何後續調用將當即返回。這種現象只出現一次,計數是不能被重置的。多線程

若是你須要一個能夠重置計數的版本,須要考慮使用CyclicBarrierapp

上面的介紹來自於CountDownLatch類的註釋。 less

/** 
 * A synchronization aid that allows one or more threads to wait until 
 * a set of operations being performed in other threads completes. 
 * 
 * <p>A {@code CountDownLatch} is initialized with a given [i]count[/i]. 
 * The {@link #await await} methods block until the current count reaches 
 * zero due to invocations of the {@link #countDown} method, after which 
 * all waiting threads are released and any subsequent invocations of 
 * {@link #await await} return immediately.  This is a one-shot phenomenon 
 * -- the count cannot be reset.  If you need a version that resets the 
 * count, consider using a {@link CyclicBarrier}. 
 * 
 */

CountDownLatch工具類相關類圖

CountDownLatch中定義了一個內部類Sync,該類繼承AbstractQueuedSynchronizer。從代碼中能夠看出,CountDownLatch的await,countDown以及getCount方法都調用了Sync的方法。異步

CountDownLatch類源代碼 

/*
 * @(#)CountDownLatch.java	1.5 04/02/09
 *
 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.util.concurrent;
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;

/**
 * A synchronization aid that allows one or more threads to wait until
 * a set of operations being performed in other threads completes.
 *
 * <p>A <tt>CountDownLatch</tt> is initialized with a given
 * [i]count[/i].  The {@link #await await} methods block until the current
 * {@link #getCount count} reaches zero due to invocations of the
 * {@link #countDown} method, after which all waiting threads are
 * released and any subsequent invocations of {@link #await await} return
 * immediately. This is a one-shot phenomenon -- the count cannot be
 * reset.  If you need a version that resets the count, consider using
 * a {@link CyclicBarrier}.
 *
 * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
 * and can be used for a number of purposes.  A
 * <tt>CountDownLatch</tt> initialized with a count of one serves as a
 * simple on/off latch, or gate: all threads invoking {@link #await await}
 * wait at the gate until it is opened by a thread invoking {@link
 * #countDown}.  A <tt>CountDownLatch</tt> initialized to [i]N[/i]
 * can be used to make one thread wait until [i]N[/i] threads have
 * completed some action, or some action has been completed N times.
 * <p>A useful property of a <tt>CountDownLatch</tt> is that it
 * doesn't require that threads calling <tt>countDown</tt> wait for
 * the count to reach zero before proceeding, it simply prevents any
 * thread from proceeding past an {@link #await await} until all
 * threads could pass.
 *
 * <p><b>Sample usage:</b> Here is a pair of classes in which a group
 * of worker threads use two countdown latches:
 * [list]
 * <li>The first is a start signal that prevents any worker from proceeding
 * until the driver is ready for them to proceed;
 * <li>The second is a completion signal that allows the driver to wait
 * until all workers have completed.
 * [/list]
 *
 * <pre>
 * class Driver { // ...
 *   void main() throws InterruptedException {
 *     CountDownLatch startSignal = new CountDownLatch(1);
 *     CountDownLatch doneSignal = new CountDownLatch(N);
 *
 *     for (int i = 0; i < N; ++i) // create and start threads
 *       new Thread(new Worker(startSignal, doneSignal)).start();
 *
 *     doSomethingElse();            // don't let run yet
 *     startSignal.countDown();      // let all threads proceed
 *     doSomethingElse();
 *     doneSignal.await();           // wait for all to finish
 *   }
 * }
 *
 * class Worker implements Runnable {
 *   private final CountDownLatch startSignal;
 *   private final CountDownLatch doneSignal;
 *   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
 *      this.startSignal = startSignal;
 *      this.doneSignal = doneSignal;
 *   }
 *   public void run() {
 *      try {
 *        startSignal.await();
 *        doWork();
 *        doneSignal.countDown();
 *      } catch (InterruptedException ex) {} // return;
 *   }
 *
 *   void doWork() { ... }
 * }
 *
 * </pre>
 *
 * <p>Another typical usage would be to divide a problem into N parts,
 * describe each part with a Runnable that executes that portion and
 * counts down on the latch, and queue all the Runnables to an
 * Executor.  When all sub-parts are complete, the coordinating thread
 * will be able to pass through await. (When threads must repeatedly
 * count down in this way, instead use a {@link CyclicBarrier}.)
 *
 * <pre>
 * class Driver2 { // ...
 *   void main() throws InterruptedException {
 *     CountDownLatch doneSignal = new CountDownLatch(N);
 *     Executor e = ...
 *
 *     for (int i = 0; i < N; ++i) // create and start threads
 *       e.execute(new WorkerRunnable(doneSignal, i));
 *
 *     doneSignal.await();           // wait for all to finish
 *   }
 * }
 *
 * class WorkerRunnable implements Runnable {
 *   private final CountDownLatch doneSignal;
 *   private final int i;
 *   WorkerRunnable(CountDownLatch doneSignal, int i) {
 *      this.doneSignal = doneSignal;
 *      this.i = i;
 *   }
 *   public void run() {
 *      try {
 *        doWork(i);
 *        doneSignal.countDown();
 *      } catch (InterruptedException ex) {} // return;
 *   }
 *
 *   void doWork() { ... }
 * }
 *
 * </pre>
 *
 * @since 1.5
 * @author Doug Lea
 */
public class CountDownLatch {
    /**
     * Synchronization control For CountDownLatch.
     * Uses AQS state to represent count.
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        Sync(int count) {
            setState(count); 
        }
        
        int getCount() {
            return getState();
        }

        public int tryAcquireShared(int acquires) {
            return getState() == 0? 1 : -1;
        }
        
        public 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;
            }
        }
    }

    private final Sync sync;
    /**
     * Constructs a <tt>CountDownLatch</tt> initialized with the given
     * count.
     * 
     * @param count the number of times {@link #countDown} must be invoked
     * before threads can pass through {@link #await}.
     *
     * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
     */
    public CountDownLatch(int count) { 
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to 
     * zero, unless the thread is {@link Thread#interrupt interrupted}.
     *
     * <p>If the current {@link #getCount count} is zero then this method
     * returns immediately.
     * <p>If the current {@link #getCount count} is greater than zero then
     * the current thread becomes disabled for thread scheduling 
     * purposes and lies dormant until one of two things happen:
     * [list]
     * <li>The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     * <li>Some other thread {@link Thread#interrupt interrupts} the current
     * thread.
     * [/list]
     * <p>If the current thread:
     * [list]
     * <li>has its interrupted status set on entry to this method; or 
     * <li>is {@link Thread#interrupt interrupted} while waiting, 
     * [/list]
     * 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);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to 
     * zero, unless the thread is {@link Thread#interrupt interrupted},
     * or the specified waiting time elapses.
     *
     * <p>If the current {@link #getCount count} is zero then this method
     * returns immediately with the value <tt>true</tt>.
     *
     * <p>If the current {@link #getCount count} is greater than zero then
     * the current thread becomes disabled for thread scheduling 
     * purposes and lies dormant until one of three things happen:
     * [list]
     * <li>The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     * <li>Some other thread {@link Thread#interrupt interrupts} the current
     * thread; or
     * <li>The specified waiting time elapses.
     * [/list]
     * <p>If the count reaches zero then the method returns with the
     * value <tt>true</tt>.
     * <p>If the current thread:
     * [list]
     * <li>has its interrupted status set on entry to this method; or 
     * <li>is {@link Thread#interrupt interrupted} while waiting, 
     * [/list]
     * then {@link InterruptedException} is thrown and the current thread's 
     * interrupted status is cleared. 
     *
     * <p>If the specified waiting time elapses then the value <tt>false</tt>
     * is returned.
     * If the time is 
     * less than or equal to zero, the method will not wait at all.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the <tt>timeout</tt> argument.
     * @return <tt>true</tt> if the count reached zero  and <tt>false</tt>
     * if the waiting time elapsed before the count reached zero.
     *
     * @throws InterruptedException if the current thread is interrupted
     * while waiting.
     */
    public boolean await(long timeout, TimeUnit unit) 
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     * <p>If the current {@link #getCount 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 {@link #getCount count} equals zero then nothing
     * happens.
     */
    public void countDown() {
        sync.releaseShared(1);
    }

    /**
     * Returns the current count.
     * <p>This method is typically used for debugging and testing purposes.
     * @return the current count.
     */
    public long getCount() {
        return sync.getCount();
    }

    /**
     * Returns a string identifying this latch, as well as its state.
     * The state, in brackets, includes the String 
     * "Count =" followed by the current count.
     * @return a string identifying this latch, as well as its
     * state
     */
    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }

}

CountDownLatch工具類的使用案例

CountDownLatch的做用

CountDownLatch的做用是控制一個計數器,每一個線程在運行完畢後執行countDown,表示本身運行結束,這對於多個子任務的計算特別有效,好比一個異步任務須要拆分紅10個子任務執行,主任務必須知道子任務是否完成,全部子任務完成後才能進行合併計算,從而保證了一個主任務邏輯的正確性。ide

(此段摘自於<<改善Java程序的151個建議>>, P254) 工具

CountDownLatch最重要的方法是countDown()和await(),前者主要是倒數一次,後者是等待倒數到0若是沒有到達0,就只有阻塞等待了。 測試

案例描述

使用CountDownLatch工具類來實現10個線程對1~100的求和,每一個線程對10個數進行求和。ui

  • 第一個線程對1 – 10的數字求和 
  • 第二個線程對 11 – 20的數字求和 
  • 第三個線程對21 – 30 的數字求和 
  • ….. 
  • 第十個線程對91 – 100的數字求和。 

代碼與測試

由於須要用到每一個線程執行後的求和結果,因此,先編寫一個用於求和計算的類並實現Callable接口,this

如:

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * 
 * @author wangmengjun
 *
 */
public class Calculator implements Callable<Integer> {

	// 開始信號
	private final CountDownLatch startSignal;

	// 結束信號
	private final CountDownLatch doneSignal;

	private int groupNumber = 0;

	/**
	 * @param startSignal
	 * @param endSignal
	 * @param groupId
	 */
	public Calculator(CountDownLatch startSignal, CountDownLatch doneSignal,
			int groupNumber) {
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
		this.groupNumber = groupNumber;
	}

	public Integer call() throws Exception {
		startSignal.await();
		Integer result = sum(groupNumber);
		printCompleteInfor(groupNumber, result);
		doneSignal.countDown();

		return result;
	}

	private Integer sum(int groupNumber) {
		if (groupNumber < 1) {
			throw new IllegalArgumentException();
		}

		int sum = 0;
		int start = (groupNumber - 1) * 10 + 1;
		int end = groupNumber * 10;
		for (int i = start; i <= end; i++) {
			sum += i;
		}
		return sum;
	}

	private void printCompleteInfor(int groupNumber, int sum) {
		System.out.println(String.format(
				"Group %d is finished, the sum in this gropu is %d",
				groupNumber, sum));
	}
}

建立10個線程,而後對結果求和。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CountDownLatchTest {

	public static void main(String[] args) throws Exception {
		/**
		 * 1-100求和,分10個線程來計算,每一個線程對10個數求和。
		 */
		int numOfGroups = 10;
		CountDownLatch startSignal = new CountDownLatch(1);
		
		CountDownLatch doneSignal = new CountDownLatch(numOfGroups);
		
		ExecutorService service = Executors.newFixedThreadPool(numOfGroups);
		List<Future<Integer>> futures = new ArrayList<Future<Integer>>();

		submit(futures, numOfGroups, service, startSignal, doneSignal);
		
		/**
		 * 開始,讓全部的求和計算線程運行
		 */
		startSignal.countDown();
		
		/**
		 * 阻塞,知道全部計算線程完成計算
		 */
		doneSignal.await();

		shutdown(service);
		
		printResult(futures);
	}

	private static void submit(List<Future<Integer>> futures, int numOfGroups,
			ExecutorService service, CountDownLatch startSignal,
			CountDownLatch doneSignal) {
		for (int groupNumber = 1; groupNumber <= numOfGroups; groupNumber++) {
			futures.add(service.submit(new Calculator(startSignal, doneSignal,
					groupNumber)));
		}
	}

	private static int getResult(List<Future<Integer>> futures)
			throws InterruptedException, ExecutionException {
		int result = 0;
		for (Future<Integer> f : futures) {
			result += f.get();
		}
		return result;
	}

	private static void printResult(List<Future<Integer>> futures)
			throws InterruptedException, ExecutionException {
		System.out.println("[1,100] Sum is :" + getResult(futures));
	}
	
	private static void shutdown(ExecutorService service)
	{
		service.shutdown();
	}

}

某次運行的結果以下:

Group 7 is finished, the sum in this gropu is 655
Group 3 is finished, the sum in this gropu is 255
Group 8 is finished, the sum in this gropu is 755
Group 10 is finished, the sum in this gropu is 955
Group 6 is finished, the sum in this gropu is 555
Group 5 is finished, the sum in this gropu is 455
Group 4 is finished, the sum in this gropu is 355
Group 1 is finished, the sum in this gropu is 55
Group 9 is finished, the sum in this gropu is 855
Group 2 is finished, the sum in this gropu is 155
[1,100] Sum is :5050

小結

本文首先對java.util.concurrent包下的CountDownLatch工具類進行了簡單的描述;接着,給出了CountDownLatch的做用;最後給出了一個使用CountDownLatch工具類完成10個線程求和的例子。

使用CountDownLatch時,它關注的一個線程或者多個線程須要在其它在一組線程完成操做以後,在去作一些事情。好比:服務的啓動等。

相關文章
相關標籤/搜索