一、CountDownLatchDemo
package com.duchong.concurrent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
/*
* CountDownLatch :阻塞主線程,等子線程完成
*/
public class CountDownLatchDemo {
/**
* 存放子線程產生的結果
*/
private static ConcurrentHashMap<String,Integer> resultMap =new ConcurrentHashMap<>();
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(5);
SubThread subThread = new SubThread(latch);
for (int i = 0; i <=4; i++) {
new Thread(subThread).start();
}
try {
//阻塞主線程
latch.await();
}
catch (InterruptedException e) {
}
//計算總結果
int sum=0;
for(Map.Entry<String,Integer> subNumber:resultMap.entrySet()){
sum +=subNumber.getValue();
}
System.out.println("sum = "+sum);
}
/**
* 子線程
*/
static class SubThread implements Runnable {
private CountDownLatch latch;
public SubThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
try {
int number = RandomUtil.getNumber();
System.out.println(name+"---number:"+number);
resultMap.put(name,number);
}
finally {
latch.countDown();
}
}
}
}

二、CyclicBarrierDemo
package com.duchong.concurrent;
import java.util.Map;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
/*
* CyclicBarrier :阻塞子線程,當等待中的子線程數到達一定數量時,跳閘。
*/
public class CyclicBarrierDemo {
/**
* 屏障,初始5 當await()的線程數量達到5時,跳閘。
*/
static CyclicBarrier c = new CyclicBarrier(5,new SumThread());
/**
* 存放子線程產生的結果
*/
private static ConcurrentHashMap<String,Integer> resultMap =new ConcurrentHashMap<>();
public static void main(String[] args) {
//模擬四個子線產生隨機數值
for(int i=0;i<=4;i++){
new Thread(new SubThread()).start();
}
}
/**
* 所有子線程等待數等於5時,執行
*/
private static class SumThread implements Runnable{
@Override
public void run() {
int result =0;
for(Map.Entry<String,Integer> workResult:resultMap.entrySet()){
result = result+workResult.getValue();
}
System.out.println("result = "+result);
}
}
/**
* 子線程
*/
static class SubThread implements Runnable{
@Override
public void run() {
String name = Thread.currentThread().getName();
int number = RandomUtil.getNumber();
System.out.println(name+"---number:"+number);
resultMap.put(name,number);
try {
//阻塞子線程
c.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
