`
543089122
  • 浏览: 149646 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

CountDownLatch、CyclicBarrier让多线程变得更简单

    博客分类:
  • java
阅读更多
CountDownLatch 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待

CyclicBarrier 一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。

这是JAVA1.5中的2个帮助类,他们2都是直接继承java.lang.Object的,目的是为了让线程之间的相互等待变得简单。


CountDownLatch的用法如下(CyclicBarrier要更加简单一些而且更加强大一些,用法参看http://www.iteye.com/topic/1116068之前写的一个测试)

package thread.concurrent.CountDownLatch;

import java.util.AbstractQueue;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
/**
 * CountDownLatch:一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
 * 用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,
 * await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。
 * 这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier。 
 */
public class CountDownLatchTest {
	public static void main(String[] args) throws InterruptedException {
		int threadCount = 10;
		CountDownLatch beginSingle = new CountDownLatch(1);
		CountDownLatch endSingle = new CountDownLatch(threadCount);
		AbstractQueue<SportsMan> queue = new ArrayBlockingQueue<SportsMan>(
				threadCount);
		for (int i = 0; i < threadCount; i++) {
			new Thread(new WorkThread(queue, beginSingle, endSingle)).start();
		}
		beginSingle.countDown();//②枪响
		endSingle.await();//③使当前线程等待,直到endSingle计数器递减到0才放开
		System.out.println("统计成绩:" + queue);
	}
}

//每个线程代表一个运动员
class WorkThread implements Runnable {
	AbstractQueue<SportsMan> queue;
	CountDownLatch countDownLatch;
	CountDownLatch endSingle;

	public WorkThread(AbstractQueue<SportsMan> queue,
			CountDownLatch countDownLatch, CountDownLatch endSingle) {
		super();
		this.queue = queue;
		this.countDownLatch = countDownLatch;
		this.endSingle = endSingle;
	}

	public void run() {
		try {
			countDownLatch.await();//①运动员各就各位

			int time = (new Random()).nextInt(10);
			System.out.println("线程:" + Thread.currentThread().getName() + "用时:"
					+ time);
			queue.add(new SportsMan(Thread.currentThread().getName(), time));

			endSingle.countDown();//③每次有人跑到终点,则结束计数器递减,当结束计数器递减到0也就是所有人都跑完了就进行成绩统计。
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

// 运动员类
class SportsMan {
	String name;
	Integer time;

	public SportsMan(String name, Integer time) {
		super();
		this.name = name;
		this.time = time;
	}

	public String toString() {
		return "{name:" + name + ",time:" + time + "}";
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics