同步屏障CyclicBarrier让一组线程到达一个屏障(同步点)时阻塞,直到最后一个线程到达屏障时,屏障打开,所有线程继续执行。
- 构造参数int parties,表示屏障拦截的线程数量,每个线程调用await()方法表示自己已经到达屏障,进入阻塞
import java.util.concurrent.CyclicBarrier;
/**
* @author pengjunzhe
*/
public class CyclicBarrierTest {
static CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(1);
}
}).start();
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(2);
}
}
- 有一个更高级的方法CyclicBarrier(int parties, Runnable barrierAction)用于在线程达到屏障点时,优先执行barrierAction:
import java.util.concurrent.CyclicBarrier;
/**
* @author pengjunzhe
*/
public class CyclicBarrierTest2 {
static CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new A());
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(1);
}
}).start();
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(2);
}
static class A implements Runnable {
@Override
public void run() {
System.out.println(3);
}
}
}
- reset()方法可以重置CyclicBarrier