并行中的顺序执行——CountDownLatch

    java.util.concurrent.CountDownLatch : 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。--《JDK API 1.6.0》

    换句话说,你可以并行的执行一段代码,并设置等待所有的线程都执行完的点,然后再一起开始执行

    举例说,五个个人一起(并行)包饺子,只有等所有的饺子都包好以后才一起下锅,得,就这个意思咯。

其API相对来说比较简单:

构造方法摘要
CountDownLatch(int count)
构造一个用给定计数初始化的 CountDownLatch
方法摘要
void await()
使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。
boolean await(long timeout, TimeUnit unit)
使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。
void countDown()
递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
long getCount()
返回当前计数。
String toString()
返回标识此锁存器及其状态的字符串。

 

从类 java.lang.Object 继承的方法
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

实例:

public class CountDownLatchDemo {
	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("zhang san", 5000, latch);
    	Worker worker2=new Worker("li si", 8000, latch);
    	worker1.start();//
    	worker2.start();//
    	latch.await();//等待所有工人完成工作点
        System.out.println("all work done at "+sdf.format(new Date()));
	}
        
    static class Worker extends Thread{
    	String workerName; 
    	int workTime;
    	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("Worker "+workerName+" do work begin at "+sdf.format(new Date()));
    		doWork();//工作了
    		System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));
    		latch.countDown();//工人完成工作,计数器减一

    	}
    	
    	private void doWork(){
    		try {
				Thread.sleep(workTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    }
         
}

实例输出:

Worker zhang san do work begin at 2015-01-03 21:26:38
Worker li si do work begin at 2015-01-03 21:26:38
Worker zhang san do work complete at 2015-01-03 21:26:43
Worker li si do work complete at 2015-01-03 21:26:46
all work done at 2015-01-03 21:26:46

 

你可能感兴趣的:(线程)