首页 > 代码库 > Java多线程之~~~使用CountDownLatch来同步多个线程实现一个任务

Java多线程之~~~使用CountDownLatch来同步多个线程实现一个任务

在多线程开发中,经常会遇到这样的问题,比如,一个线程需要其他的一些辅助线程完成指定的一些任务后才能开

启。 类似于一个主线程正在运行,他需要其他分支线程完成一些任务后才能激活他来启动剩下的任务,这里就可以使用

Java自带的CountDownLatch这个类来帮我们实现这样的效果。   这个类初始化的时候会指定一个数字,这就是需要等

待的资源的数量,每一个资源到位的时候,就调用他的countDown函数,这样就会将资源减一,知道这个资源数字变成

0的时候 ,就会叫醒主线程,来完成剩下的功能,下面我们就使用一个例子来说明这样的情况。


package com.bird.concursey.charpet4;

import java.util.concurrent.CountDownLatch;

public class Videoconference implements Runnable {
	
	private CountDownLatch controller;
	
	/**
	 * Implement the constructor of the class that initializes the CountDownLatch
attribute. The Videoconference class will wait for the arrival of the number of
participants received as a parameter.
	 * @param number
	 */
	public Videoconference(int number) {
		controller = new CountDownLatch(number);
	}
	
	public void arrive(String name) {
		System.out.printf("%s has arrived.",name);
		controller.countDown();
		System.out.printf("VideoConference: Waiting for %d participants.\n",controller.getCount());
	}
	
	@Override
	public void run() {
		System.out.printf("VideoConference: Initialization: %d participants.\n",controller.getCount());
		try {
			controller.await();
			System.out.printf("VideoConference: All the participants have come\n");
			System.out.printf("VideoConference: Let's start...\n");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}



package com.bird.concursey.charpet4;

import java.util.concurrent.TimeUnit;

public class Participant implements Runnable {
	
	private Videoconference videoConference;
	
	private String name;
	
	public Participant(Videoconference videoConference, String name) {
		this.videoConference = videoConference;
		this.name = name;
	}


	@Override
	public void run() {
		long duration=(long)(Math.random()*10);
		try {
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		videoConference.arrive(name);
	}
	
	public static void main(String[] args) {
		//Create a Videoconference object named conference that waits for 10 participants.
		Videoconference videoCOnference = new Videoconference(10);
		Thread threadConference = new Thread(videoCOnference);
		threadConference.start();
		
		for(int i = 0; i < 10; i++) {
			Participant participant = new Participant(videoCOnference, "participant" + i);
			Thread t = new Thread(participant);
			t.start();
		}
	}

}


Java多线程之~~~使用CountDownLatch来同步多个线程实现一个任务