CountDownLatch Example

package com.jibx_maven;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
/**
 * 
 * <li>The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed; </li>
 *<li>The second is a completion signal that allows the driver to wait until all workers have completed. </li>
 *
 */

public class CountDownLatchExample {
	
	public static void main(String[] args) {
		
		CountDownLatch startSignal = new CountDownLatch(1);
		CountDownLatch doneSignal = new CountDownLatch(4);
		new Thread(new Workders(startSignal, doneSignal, "A")).start();;
		new Thread(new Workders(startSignal, doneSignal, "B")).start();;
		new Thread(new Workders(startSignal, doneSignal, "C")).start();
		new Thread(new Workders(startSignal, doneSignal, "D")).start();;
		new Thread(new Driver(startSignal, doneSignal)).start();;
	}

}
class Driver implements Runnable{
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;
	private Random random = new Random();
	
	public Driver(CountDownLatch startSignal, CountDownLatch doneSignal) {
		super();
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
	}

	@Override
	public void run() {
		sendInRawMaterial();
		sendOutProduct();
		
	}
	public void sendInRawMaterial()
	{
		System.out.println("driver is sending in some raw materials");
		try {
			Thread.sleep(random.nextInt(10)*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("raw materials arrived");
		startSignal.countDown();
	}
	public void sendOutProduct()
	{
		try {
			doneSignal.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("all raw material have been made product");
		System.out.println("driver is sending out the product");
		
	}
	
}
class Workders implements Runnable{
	 private final CountDownLatch startSignal;
	 private final CountDownLatch doneSignal;
	 private String workerId;
	 
	public Workders(CountDownLatch startSignal, CountDownLatch doneSignal,String workerId) {
		super();
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
		this.workerId = workerId;
	}

	@Override
	public void run() {
		try {
			startSignal.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("worker "+workerId +" is to start working");
		Random random = new Random();
		try {
			Thread.sleep(random.nextInt(20)*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("worker "+workerId +" finished his work");
		doneSignal.countDown();
		
	}
	
}

你可能感兴趣的:(thread)