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

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值