CountDownLatchとCyclicBarrier

1508 ワード


CountDownLath:マルチタスククエリーに使用され、すべてのタスクが戻るかタイムアウトするシーンを待つのに適しています.次のようになります.
 
 
  
class CountDownLatchJob implements Runnable{
	private CountDownLatch latch;
	private String name;
	private int waitTime;
	
	public CountDownLatchJob (CountDownLatch latch,
                                  String name,int waitTime) {
		this.latch = latch;
		this.name= name;
                this.waitTime=waitTime;
	}

	@Override
	public void run() {
	  try {
	   	  TimeUnit.MILLISECONDS.sleep(waitTime);
		   System.out.println(name+ " completed!");
	      } catch (InterruptedException e) {
		   e.printStackTrace();
	      }finally{
                     latch.countDown();
              }
	}
}

public class Test{
	 
	public static void main(String[] args) {
             int threadNum = 10;
             Random random = new Random();  
             CountDownLatch latch = new CountDownLatch(threadNum );
             for(int i = 0; i < threadNum ; i++){
                 new CountDownLatchJob (latch,"job"+i, 
                      r.nextInt(i*1000).start();
	     }	
              latch.await();//latch.await(timout);
	      System.out.println("All Job has Completed!");
	}
}

 
CyclicBarrierリファレンス:http://www.iteye.com/topic/711162