Talk is cheap.Show the code!
public class MyCyclicBarrier_1 extends Thread{
private CyclicBarrier cyclicBarrier;
public MyCyclicBarrier_1(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
System.out.println("Thread start."+Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2); //业务模拟code
System.out.println("Thread "+Thread.currentThread().getName()+" is waiting for the other Threads."+
"\n\t\t\t\tIt's parties is "+cyclicBarrier.getParties()+
"\n\t\t\t\tWaiting for "+cyclicBarrier.getNumberWaiting()+" Threads");
cyclicBarrier.await(3,TimeUnit.SECONDS);
} catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
e.printStackTrace();
}
System.out.println("Thread end."+Thread.currentThread().getName());
}
}
测试代码
public class TestCyclicbarrier_1 {
public static void main(String[] args) {
int length = 5;
long start = System.currentTimeMillis();
CyclicBarrier cyclicBarrierWithRunnable = new CyclicBarrier(length,()->{
System.out.println("the final reach Thread is "+Thread.currentThread().getName());
long end = System.currentTimeMillis();
System.out.println("cost totally :"+(end-start)/1000+"s");
});
for (int i=0;i<length;i++){
if (i!=4){
new MyCyclicBarrier_1(cyclicBarrierWithRunnable).start();
}else {
try {
TimeUnit.SECONDS.sleep(2); //若是这里改成3s会抛出超时异常
new MyCyclicBarrier_1(cyclicBarrierWithRunnable).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
输出:
Thread start.Thread-1
Thread start.Thread-0
Thread start.Thread-2
Thread start.Thread-3
Thread Thread-0 is waiting for the other Threads.
It's parties is 5
Waiting for 0 Threads
Thread Thread-3 is waiting for the other Threads.
It's parties is 5
Waiting for 0 Threads
Thread start.Thread-4
Thread Thread-1 is waiting for the other Threads.
It's parties is 5
Waiting for 0 Threads
Thread Thread-2 is waiting for the other Threads.
It's parties is 5
Waiting for 1 Threads
Thread Thread-4 is waiting for the other Threads.
It's parties is 5
Waiting for 4 Threads
the final reach Thread is Thread-4
cost totally :4s
Thread end.Thread-4
Thread end.Thread-0
Thread end.Thread-3
Thread end.Thread-2
Thread end.Thread-1
问题一眼就能看出来了,0至3这三条线程在2s的时候就已经“到达了”屏障点,CyclicBarrier.await(3s)。为什么线程4(最后执行的这条线程)沉睡了2s后再执行2秒的业务代码(共4秒),不会使得CyclicBarrier.await(3s)抛出超时异常呢?
已分析出答案,此贴可结。