public class Test{
//等待某个条件为真 执行
static void countDown() throws InterruptedException{
//主线程控制 所有子线程 执行
final CountDownLatch start = new CountDownLatch(1);
//主线程等待 所有子线程 执行完毕
final CountDownLatch end = new CountDownLatch(10);
for( int i=0;i<10;i++){
final int index = i;
Thread t = new Thread(){
@Override
public void run() {
try {
//等待start的数量为零再执行
start.await();
System.out.println("thread " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
end.countDown();
}
}
};
t.start();
}
long s = System.nanoTime();
start.countDown();
//等待end的数量为零再执行
end.await();
long e = System.nanoTime();
System.out.println("time=" + (e-s));
}
//等待所有线程完成
static void cyclicBarrier(){
//全局缓存
final Map<Integer,Long> map = new ConcurrentHashMap<Integer,Long>();
//合计线程 计算总数
final CyclicBarrier barrier = new CyclicBarrier(5, new Runnable(){
@Override
public void run() {
for(Integer t : map.keySet()){
System.out.println("sub=" + t + "Value="+map.get(t));
}
}
} );
//子计算线程1
new Compute(1,barrier,10000L,map).start();
//子计算线程2
new Compute(2,barrier,99990000L,map).start();
//子计算线程3
new Compute(3,barrier,10000L,map).start();
//子计算线程4
new Compute(4,barrier,99990000L,map).start();
//子计算线程5
new Compute(5,barrier,10000L,map).start();
}
static class Compute extends Thread{
private CyclicBarrier barrier ;
private Integer index ;
private Long i;
Map<Integer,Long> map;
public Compute(Integer index ,CyclicBarrier barrier,Long i,Map<Integer,Long> map){
this.barrier = barrier;
this.index = index;
this.i = i;
this.map = map;
}
private Long sum(){
Long sum = 0L;
for(Long j=0L ;j<i; j++){
sum = sum + j;
}
return sum;
}
@Override
public void run() {
map.put(index, sum());
try {
//通知barrier当前线程计算完成
barrier.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//countDown();
cyclicBarrier();
}
}