同步辅助类CyclicBarrier
它允许一组线程互相等待,直到到达某个公共屏障点 ,类似于坐过山车,一定要等5个人才发车
案例:
package Lock;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
final CyclicBarrier cb = new CyclicBarrier(5);
for (int i = 0; i < 5; i++) {
Runnable run = new Runnable() {
@Override
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合点1,当前已有"
+ (cb.getNumberWaiting() + 1) + "到达");
if ((cb.getNumberWaiting() + 1) == 5) {
System.out.println("都到齐了,继续走");
}
cb.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合点2,当前已有"
+ (cb.getNumberWaiting() + 1) + "到达");
if ((cb.getNumberWaiting() + 1) == 5) {
System.out.println("都到齐了,继续走");
}
cb.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合点3,当前已有"
+ (cb.getNumberWaiting() + 1) + "到达");
if ((cb.getNumberWaiting() + 1) == 5) {
System.out.println("都到齐了,继续走");
}
cb.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
executorService.execute(run);
}
executorService.shutdown();
}
}
运行结果:
线程pool-1-thread-5即将到达集合点1,当前已有1到达
线程pool-1-thread-3即将到达集合点1,当前已有2到达
线程pool-1-thread-4即将到达集合点1,当前已有3到达
线程pool-1-thread-2即将到达集合点1,当前已有4到达
线程pool-1-thread-1即将到达集合点1,当前已有5到达
都到齐了,继续走
线程pool-1-thread-5即将到达集合点2,当前已有1到达
线程pool-1-thread-2即将到达集合点2,当前已有2到达
线程pool-1-thread-3即将到达集合点2,当前已有3到达
线程pool-1-thread-1即将到达集合点2,当前已有4到达
线程pool-1-thread-4即将到达集合点2,当前已有5到达
都到齐了,继续走
线程pool-1-thread-3即将到达集合点3,当前已有1到达
线程pool-1-thread-5即将到达集合点3,当前已有2到达
线程pool-1-thread-4即将到达集合点3,当前已有3到达
线程pool-1-thread-1即将到达集合点3,当前已有4到达
线程pool-1-thread-2即将到达集合点3,当前已有5到达
都到齐了,继续走