CyclicBarrier计数器当给定的所有线程都处于等待状态时开始运行。
比如有这样一个例子:
5个人参加赛跑,在开跑前要确定所有人都处于准备状态,
5个人用5个线程代表,在赛跑前有个准备 3 2 1的口号
代码如下:
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Person implements Runnable {
public int counter = 0;
CyclicBarrier mCyclicBarrier;
private Random random=new Random(System.currentTimeMillis());
public Person(CyclicBarrier mCyclicBarrier, int id) {
this.mCyclicBarrier = mCyclicBarrier;
this.counter = id;
}
private void runTime(){
try {
Thread.sleep(1000+random.nextInt(2000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
try {
System.out.println("Person" + counter + " ready");
mCyclicBarrier.await();
System.out.println("Person" + counter + " running");
runTime();
System.out.println("Person" + counter + " reach end");
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Test {
static ExecutorService exec = Executors.newCachedThreadPool();
public static void main(String[] args) {
CyclicBarrier mCyclicBarrier = new CyclicBarrier(5, new Runnable() {
@Override
public void run() {
try {
System.out.println("ready");
Thread.sleep(800);
System.out.println("3");
Thread.sleep(800);
System.out.println("2");
Thread.sleep(800);
System.out.println("1");
Thread.sleep(800);
System.out.println("go");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
for (int i = 0; i < 5; i++) {
exec.execute(new Person(mCyclicBarrier, i));
}
}
}
CyclicBarrier初始化时规定一个数目,然后计算调用了CyclicBarrier.await()进入等待的线程数。当线程数达到了这个数目时,所有进入等待状态的线程被唤醒并继续。
CyclicBarrier初始时还可带一个Runnable的参数, 此Runnable任务在CyclicBarrier的数目达到后,所有其它线程被唤醒前被执行
CyclicBarrier计数器的使用
最新推荐文章于 2022-02-12 20:25:34 发布