关于多线程同步的初步教程--Barrier的设计及使用

本文介绍了多线程同步的重要工具CyclicBarrier,详细讲解了其内部工作原理,包括parties、broken状态以及barrier方法的实现。通过示例展示了如何在并发编程中使用CyclicBarrier协调线程,特别是在解决多线程协作问题上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Barrier是一个多线程编程中经常要用到的同步工具,尤其多用于大数据量的计算过程中的同步。本文以广为流程的Doug Lea的concurrent工具包的Barrier实现为例,进行一点探讨。在Doug Lea的concurrent工具包中,Barrier是一个接口,在concurrent包中提供了两个Barrier的实现:CyclicBarrier和Rendezvous。下面是Barrier接口的定义:

  1. public interface Barrier {
  2.  
  3.  
  4.   /** 
  5.    * Return the number of parties that must meet per barrier
  6.    * point. The number of parties is always at least 1.
  7.    **/
  8.  
  9.   public int parties();
  10.  
  11.   /**
  12.    * Returns true if the barrier has been compromised
  13.    * by threads leaving the barrier before a synchronization
  14.    * point (normally due to interruption or timeout). 
  15.    * Barrier methods in implementation classes throw
  16.    * throw BrokenBarrierException upon detection of breakage.
  17.    * Implementations may also support some means
  18.    * to clear this status.
  19.    **/
  20.  
  21.   public boolean broken();
  22. }


    Barrier接口中的方法非常简单,parties()返回所有需要在屏障处同步的线程数;broken()返回一个标志,指示释放是否已被破坏。Barrier接口中并没有提供加入屏障的方法,而是在c和Rendezvous的Barrier实现中提供的。你可以会疑问,为什么不在Barrier接口中提供这些方法呢?因为这些实现的差异迥异,以至于很难在这些实现中提炼出一个共用的方法签名。比如,对于CyclicBarrier加入屏障的方法是:barrier(), 

  1. // CyclicBarrier.java
  2.   public int barrier() throws InterruptedException, BrokenBarrierException {
  3.     return doBarrier(false, 0);
  4.   }
  5.  
  6.   protected synchronized int doBarrier(boolean timed, long msecs) 
  7.     throws InterruptedException, TimeoutException, BrokenBarrierException  { 
  8.     
  9.     int index = --count_;
  10.  
  11.     if (broken_) {
  12.       throw new BrokenBarrierException(index);
  13.     }
  14.     else if (Thread.interrupted()) {
  15.       broken_ = true;
  16.       notifyAll();
  17.       throw new InterruptedException();
  18.     }
  19.     else if (index == 0) {  // tripped
  20.       count_ = parties_;
  21.       ++resets_;
  22.       notifyAll();
  23.       try {
  24.        &nbs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值