CyclicBarrier是一个线程辅助类,在初始化时,指定所要等待的线程等待数,调用await方法会使线程处于等待状态,直到等待的线程数达到指定的数。
下面是小实例:
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 线程等待器
* @author YangBaoBao
*
*/
public class CyclicBarrierDemo {
public static void main(String[] args) {
ExecutorService service=Executors.newCachedThreadPool();
final CyclicBarrier barrier = new CyclicBarrier(5);
for (int i = 0; i < 5; i++) {
Runnable runnable = new Runnable() {
public void run() {
try {
Thread.sleep(new Random().nextInt(2000));
System.out.println("1正在等待的线程有:"+barrier.getNumberWaiting()+" 个");
barrier.await();
System.out.println("1人数到全:"+barrier.getParties()+" go");
Thread.sleep(new Random().nextInt(2000));
System.out.println("2正在等待的线程有:"+barrier.getNumberWaiting()+" 个");
barrier.await();
System.out.println("2人数到全:"+barrier.getParties()+" go");
} catch (Exception e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
}
}