import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CyclicBarrierTest {
public static final int N = 5;
public static void main(String[] args) {
System.out.println("----等待汇总-----");
CyclicBarrier barrier = new CyclicBarrier(N, new TotalTask());
ExecutorService service = Executors.newCachedThreadPool();
for (int i = 0; i < N; i++) {
service.execute(new BillTask(barrier));
}
service.shutdown();
}
}
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class BillTask extends Thread {
private CyclicBarrier barrier;
BillTask(CyclicBarrier barrier) {
this.barrier = barrier;
}
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " 开始计算...");
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(name + " 计算完成,等待汇总!");
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
public class TotalTask implements Runnable {
public void run() {
System.out.println("----开始汇总----");
}
}
Console
----等待汇总-----
pool-1-thread-1 开始计算...
pool-1-thread-3 开始计算...
pool-1-thread-2 开始计算...
pool-1-thread-4 开始计算...
pool-1-thread-5 开始计算...
pool-1-thread-1 计算完成,等待汇总!
pool-1-thread-4 计算完成,等待汇总!
pool-1-thread-2 计算完成,等待汇总!
pool-1-thread-5 计算完成,等待汇总!
pool-1-thread-3 计算完成,等待汇总!
----开始汇总----
参考:http://www.iteye.com/topic/980944