Java CountDownLatch

CountDownLatch简介
          CountDownLatch是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
CountDownLatch和CyclicBarrier的区别
(1) CountDownLatch的作用是允许1或N个线程等待其他线程完成执行;而CyclicBarrier则是允许N个线程相互等待。
(2) CountDownLatch的计数器无法被重置;CyclicBarrier的计数器可以被重置后使用,因此它被称为是循环的barrier。

应用场景

       CountDownLatch的一个非常典型的应用场景是:有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行。假如我们这个想要继续往下执行的任务调用一个CountDownLatch对象的await()方法,其他的任务执行完自己的任务后调用同一个CountDownLatch对象上的countDown()方法,这个调用await()方法的任务将一直阻塞等待,直到这个CountDownLatch对象的计数值减到0为止。

         举个例子,有一个任务分为两步:下载文件和解析文件,解析线程必须等到下载线程完成后才可以干活。记住这个条件:下载任务完成后,解析任务才开始解析。所以在这里用Java代码设计两个类,Downloader代表下载任务,Parser代表解析任务,具体的代码实现如下:

Downloader.java

package com.ricky.java.common.download.test.countdownlatch;

import java.util.concurrent.CountDownLatch;

public class Downloader implements Runnable{
	private CountDownLatch latch;
	private int id;
	public Downloader(int id,CountDownLatch latch){
		this.id = id;
		this.latch = latch;
	}
	
	@Override
	public void run() {
		
		download();
	}

	private void download() {
		
		try {
			System.out.println("Worker_"+id+" start work");
			
			Thread.sleep(2000*id);
			latch.countDown();
			
			System.out.println("Worker_"+id+" finish work");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

Parser.java

package com.ricky.java.common.download.test.countdownlatch;

import java.util.concurrent.CountDownLatch;

public class Parser implements Runnable {
	private CountDownLatch latch;
	public Parser(CountDownLatch latch){
		this.latch = latch;
	}
	@Override
	public void run() {
		
		try {
			latch.await();
			System.out.println("All work has done,begin parser");
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

CountDownLatchTest.java

package com.ricky.java.common.download.test.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/***
 * CountDownLatch 使用教程
 * @author Bingbing Feng
 * @version 2014-08-20 16:25
 *
 */
public class CountDownLatchTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ExecutorService executor = Executors.newFixedThreadPool(5);
		
		CountDownLatch latch = new CountDownLatch(4);
		for(int i=1;i<=4;i++){
			Downloader worker = new Downloader(i,latch);
			executor.execute(worker);
		}
		
		executor.execute(new Parser(latch));
	}

}





你可能感兴趣的:(Java CountDownLatch)