java 多线程中 - 栅栏 就是用一个线程去等待,被唤醒的次数,如果次数和要等待的次数相同时开始执行
其原理个人理解:
设置一个线程安全的变量 CyclicBarrier barrier 中的一个计数变量 ,然后创建一个等待线程,一直wait 等待 这个计数变量修改时唤醒,
唤醒时然后判断该计数变量和创建时的 等待线程数进行比较,如果大于或者等于时,开始执行跳过wait
需要等待的线程每次执行完都需要调用barrier.await() 去修改这个计数变量
public class Test {
public static void startE() {
System.out.println("start E");
}
public static void main(String[] args) {
final int count = 3;
final CyclicBarrier barrier = new CyclicBarrier(count, new Runnable() {
@Override
public void run() {
for(int i=0;i<8;i++){
System.out.println("E "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
String [] Ids = {"A", "B", "C"};
int[] times = {2,4,5};
for (int i = 0; i < count; i++) {
new Thread(new Worker(Ids[i],times[i], barrier)).start();
}
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i= 0 ;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("D "+i);
}
}
}).start();
}
}
class Worker implements Runnable {
final String id;
final CyclicBarrier barrier;
int times =0;
public Worker(final String ids,int times, final CyclicBarrier barrier) {
this.id = ids;
this.barrier = barrier;
this.times = times;
}
@Override
public void run() {
try {
for(int i=0;i<times;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(id+" "+i);
}
this.barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}