CyclicBarriar
相关文章:
使用场景:
多个线程相互等待,直到都满足条件之后,才能执行后续的操作。CyclicBarrier描述的是各个线程之间相互等待的关系。
使用场景:
- 正常实例化:CyclicBarrier sCyclicBarrier=new CyclicBarrier(3);
- 带runnable的实例化,打破屏障时,优先执行Runnable:CyclicBarrier sCyclicBarrier=new CyclicBarrier(3,new Runnable(){//todo});
- await线程:sCyclicBarrier.await();
- 当wait线程数量为,count值时。唤醒所有等待线程。
代码示例:
1.正常实例化:
/**
* 作者:jtl
* 日期:Created in 2019/7/29 17:32
* 描述:CyclicBarrier示例
* 更改:
*/
class CyclicBarrierExample1 {
private static int count=20;
private static CyclicBarrier sCyclicBarrier=new CyclicBarrier(5);
public static void main(String[] args) throws Exception{
ExecutorService executorService= Executors.newCachedThreadPool();
for (int i=0;i<count;i++){
int threadNum=i;
Thread.sleep(1000);
executorService.execute(()->{
try {
Thread.currentThread().setName("executorService:"+threadNum);
test(threadNum);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("InterruptedException:"+e.getMessage());
} catch (BrokenBarrierException e) {
e.printStackTrace();
System.out.println("BrokenBarrierException:"+e.getMessage());
}
});
}
//关闭线程池
executorService.shutdown();
}
private static void test(int threadNum) throws InterruptedException, BrokenBarrierException {
System.out.println("wait:"+threadNum+" ThreadName: "+Thread.currentThread().getName());
sCyclicBarrier.await();
System.out.println("continue:"+threadNum+" ThreadName: "+Thread.currentThread().getName());
}
}
- 带runnable的实例化:
/**
* 作者:jtl
* 日期:Created in 2019/7/30 19:40
* 描述: 带Runnable的CyclicBarrier示例
* 更改:
*/
class CyclicBarrierExample2 {
private static int count=20;
private static CyclicBarrier sCyclicBarrier=new CyclicBarrier(5, () ->
System.out.println("Runnable is running")
);
public static void main(String[] args) throws Exception{
ExecutorService executorService= Executors.newCachedThreadPool();
for (int i=0;i<count;i++){
int threadNum=i;
Thread.sleep(1000);
executorService.execute(()->{
try {
Thread.currentThread().setName("executorService:"+threadNum);
test(threadNum);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("InterruptedException:"+e.getMessage());
} catch (BrokenBarrierException e) {
e.printStackTrace();
System.out.println("BrokenBarrierException:"+e.getMessage());
}
});
}
//关闭线程池
executorService.shutdown();
}
private static void test(int threadNum) throws InterruptedException, BrokenBarrierException {
System.out.println("wait:"+threadNum+" ThreadName: "+Thread.currentThread().getName());
sCyclicBarrier.await();
System.out.println("continue:"+threadNum+" ThreadName: "+Thread.currentThread().getName());
}
}
网友评论