瘋狂

          STANDING ON THE SHOULDERS OF GIANTS
          posts - 481, comments - 486, trackbacks - 0, articles - 1
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          Condition

          Posted on 2011-10-17 17:28 瘋狂 閱讀(686) 評論(0)  編輯  收藏 所屬分類: concurrent

          Condition(條件)Object 監視器方法(waitnotifynotifyAll)分解成截然不同的對象,以便通過將這些對象與任意 Lock 實現組合使用,為每個對象提供多個等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和語句的使用,Condition 替代了 Object 監視器方法的使用。
          下面解釋下Condition api里面的例子(生產者,消費者):

          public class ConditionTest {

           final Lock lock = new ReentrantLock();
               final Condition notFull  = lock.newCondition(); //生產者的前提條件,沒有達到次條件就阻塞
               final Condition notEmpty = lock.newCondition(); //消費者的前提條件,沒有達到次條件就阻塞
            
               final Object[] items = new Object[100];
               int putptr, takeptr, count;
            //生產
               public void put(Object x) throws InterruptedException {
                 lock.lock();
                 try {
                   while (count == items.length)//如果滿了,就讓需要條件為:沒滿的的線程(生產者)等
                     notFull.await();
                   items[putptr] = x;
                   if (++putptr == items.length) putptr = 0;
                   ++count;
                   notEmpty.signal();//如果已經生產了,就讓需要條件為不為空的線程(消費者)執行
                 } finally {
                   lock.unlock();
                 }
               }
            //消費
               public Object take() throws InterruptedException {
                 lock.lock();
                 try {
                   while (count == 0)//如果為空就讓需要條件為不為空的線程(消費者)等
                     notEmpty.await();
                   Object x = items[takeptr];
                   if (++takeptr == items.length) takeptr = 0;
                   --count;
                   notFull.signal();//如果消費了,就讓條件為不滿的線程(生產者)執行
                   return x;
                 } finally {
                   lock.unlock();
                 }
               }
             }

           


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 蓝山县| 黄龙县| 沛县| 巴青县| 牟定县| 海南省| 安溪县| 永仁县| 密山市| 临湘市| 三江| 玉龙| 同仁县| 古丈县| 资溪县| 大悟县| 石阡县| 隆安县| 东明县| 寿宁县| 彭水| 龙胜| 洱源县| 宝丰县| 巨鹿县| 乐至县| 沂源县| 博湖县| 芦溪县| 额敏县| 吉林省| 本溪| 开化县| 石嘴山市| 鄂托克前旗| 乌兰浩特市| 阿坝县| 延安市| 高雄县| 综艺| 昂仁县|