码迷,mamicode.com
首页 > 其他好文 > 详细

CountDownLatch的用法

时间:2015-04-25 21:15:52      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:多线程

CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。


主要方法
 public CountDownLatch(int count);
 public void countDown();

 public void await() 

举例:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
	private final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch=new CountDownLatch(2);//两个工人的协作  
        Worker worker1=new Worker("bao", 2000, latch);  
        Worker worker2=new Worker("senan", 4000, latch);  
        worker1.start();  
        worker2.start(); 
        latch.await();	//等待所有worker完成工作  
        System.out.println("all work done at "+sdf.format(new Date()));  	}
	static class Worker extends Thread{
		private String workerName;
		private int workTime;
		private CountDownLatch latch;
		public Worker(String workerName, int workTime, CountDownLatch latch){
			this.workerName = workerName;
			this.workTime = workTime;
			this.latch = latch;
		}
		public void run(){
			System.out.println(workerName + " start at" + sdf.format(new Date()));
			try {
				Thread.sleep(workTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally{
				latch.countDown();	//计数器减一
			}
			System.out.println(workerName + " end at" + sdf.format(new Date()));
		}
	}
}


CountDownLatch的用法

标签:多线程

原文地址:http://blog.csdn.net/kkgbn/article/details/45273967

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!