要使多个线程在做完某个操作,等其他线程做完同样的操作后,同时运行,就要用到CyclicBarrier,代码:
package com.concurrent;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import junit.framework.TestCase;
public class TestCyclicBarrier extends TestCase {
private final int COUNT = 10;
public void testCyclicBarrier() {
final CyclicBarrier cb = new CyclicBarrier(COUNT);
ExecutorService executorService = Executors.newFixedThreadPool(COUNT);
for (int i = 0; i < COUNT; i++) {
final int index = i + 1;
Runnable r = new Runnable() {
@Override
public void run() {
try {
System.out.println("wait " + index);
cb.await();
System.out.println("begin " + index);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
};
executorService.submit(r);
}
executorService.shutdown();
}
}
输出:
wait 1
wait 2
wait 4
wait 3
wait 5
wait 6
wait 7
wait 8
wait 9
wait 10
begin 10
begin 2
begin 4
begin 1
begin 3
begin 7
begin 8
begin 9
begin 6
begin 5
看到都是wait之后才输出begin,没有哪个begin是夹在两个wait之间的。