CyclicBarrier 使用说明

时间:2023-07-06 21:57:14
字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。
主要方法:
     public int await() throws InterruptedException, BrokenBarrierException
     用来挂起当前线程,直至所有线程都到达barrier状态再同时执行后续任务。
例子:
     跟团旅游,没到一个景点导游给介绍完后,让大家*活动,然后约定好(某个时间)在下一个景点集合。
 import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class CyclicBarrierTest { public static void main(String[] args) {
ExecutorService service = Executors. newCachedThreadPool();
final CyclicBarrier cb = new CyclicBarrier(3);
for(int i = 0; i < 3; i++){
Runnable runnable = new Runnable(){
public void run(){
try {
Thread. sleep((long)(Math. random()*10000));
System. out.println("线程" + Thread.currentThread().getName() +
"即将到达集合地点1,当前已有" + (cb.getNumberWaiting()+1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候" ));
cb.await(); Thread. sleep((long)(Math. random()*10000));
System. out.println("线程" + Thread.currentThread().getName() +
"即将到达集合地点2,当前已有" + (cb.getNumberWaiting()+1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候" ));
cb.await();
Thread. sleep((long)(Math. random()*10000));
System. out.println("线程" + Thread.currentThread().getName() +
"即将到达集合地点3,当前已有" + (cb.getNumberWaiting() + 1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候" ));
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
service.shutdown();
}
}