黑马程序员学习笔记——CounDownLatch、Exchange

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

CountDownLatch:java.util.concurrent中的一个实用工具类,犹如一个倒时器,用于在保持给定数目的信号、事件或条件前阻塞执行。但不能重置计数(如需重置,可考虑用同包中的另一个工具:CyclicBarrier)。

CountDownLatch效用的一个形象例子:N个运动员等待一个裁判的起跑口令(多个线程在await中,等待另一个线程来countDown),起跑后裁判等待所有运动员都到达终点后开始统计成绩(一个线程在await,等待其他多个线程来countDown).


Exchanger:同样java.util.concurrent中的一个实用工具类,它允许两个线程在 collection 点交换对象,它在多流水线设计中是有用的。


CountDownLatch范例:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {

	public static void main(String[] args) {
		final CountDownLatch cdl1 = new CountDownLatch(3);
		final CountDownLatch cdl2 = new CountDownLatch(1);
		ExecutorService es = Executors.newFixedThreadPool(3);
		for (int i=0; i<3; i++) {
			es.execute(new Runnable() {
				public void run() {
					try {
						System.out.println(Thread.currentThread().getName()+"准备就绪");
						cdl2.await();
						System.out.println(Thread.currentThread().getName()+"开跑");
						Thread.sleep((long)(Math.random()*10000));
						System.out.println(Thread.currentThread().getName()+"到达终点");
						cdl1.countDown();	//通知裁判
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		es.shutdown();
		try {
			Thread.sleep(3000); 	//3秒后起跑
			cdl2.countDown();
			cdl1.await();
			System.out.println("统计成绩");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

}

Exchanger范例

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerDemo {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		final Exchanger<String> ex = new Exchanger<String>();
		ExecutorService es = Executors.newFixedThreadPool(2);
		
		for (int i=0; i<2; i++) {
			final int id = i;
			es.submit(new Callable<Integer>() {
				String str = "线程"+id;
				public Integer call() throws Exception {
					Thread.sleep(new Random().nextInt(10000));
					System.out.println(Thread.currentThread().getName()+"正准备换数据 "+str);
					str = ex.exchange(str);
					System.out.println(Thread.currentThread().getName()+" "+str);
					return 100;
				}
			});
		}
		es.shutdown();
	}

}


---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值