瘋狂

          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();
                 }
               }
             }

           


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


          網站導航:
           
          主站蜘蛛池模板: 固原市| 始兴县| 嘉义县| 思南县| 沂水县| 宿迁市| 德保县| 岳西县| 咸阳市| 昌江| 木兰县| 颍上县| 三原县| 囊谦县| 科尔| 通渭县| 西吉县| 阜康市| 班玛县| 铜川市| 保山市| 蓝山县| 桐城市| 阿图什市| 吉木乃县| 甘洛县| 建阳市| 洛扎县| 胶州市| 维西| 来凤县| 通化市| 昆明市| 额济纳旗| 民权县| 堆龙德庆县| 赣州市| 嵩明县| 香格里拉县| 申扎县| 万山特区|