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

来源:互联网 发布:matlab2016a mac 破解 编辑:程序博客网 时间:2024/04/29 04:54

---------------------- 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
原创粉丝点击