cuiyi's blog(崔毅 crazycy)

          記錄點(diǎn)滴 鑒往事之得失 以資于發(fā)展
          數(shù)據(jù)加載中……

          java基礎(chǔ)(五):Java同步機(jī)制之notify vs notifyAll

          use the wait-and-notify mechanism to deal with synchronized accessing a resource

          wait-and-notify mechanism
          1 wait & notify can never be out of synchronized block of the releated-object (wait和notify方法必須在與之對應(yīng)的對象的同步塊里調(diào)用)
          2 wait can release & get the lock automatically

          the difference between notify and notifyAll
          1 notify is wake the thread which invoke the wait-method
          2 notifyAll is wake all the thread waiting for the lock released
          3 why can form the thread invoking the wait-method and threads waiting for the lock released?
          ?? we know, if a synchronized method is invoked, all the other synchronized methods belong to the object can not be invoked, so the invoking threads must be blocked, and waiting the method can be invoke, so they all waite for the?lock released in the list of waiting queue.
          ?? a?synchronized class is the same;
          ?? when the notify method occurs, the waiting one who invoked wait() be wake;
          ???when the notifyAll method occurs, the waiting queue choose the most?prior one to wake, can be the one invoking wait(), also can be the ones waiting the lock released;


          what we should be care?
          if?one waiting thread is?waked, its waiting condition may not be?satisfied.?and?in the right way, it should wait continuely.
          how we assure this route??
          --just as follows came?from <Effective Java> and <Practical Java>
          the former: Never invoke wait outside a loop
          ? eg:?
          ?
          1synchronized(obj)?{
          2????while(<condition?does?not?hold>)?{
          3???????wait();?
          4????????//?Perform?action?appropriate?to?condition
          5????? ?}

          6?}

          the later: Use spin locks to deal with wait and notifyAll

          posted on 2007-01-24 20:14 crazycy 閱讀(3589) 評論(0)  編輯  收藏 所屬分類: JavaSE語言

          主站蜘蛛池模板: 香河县| 基隆市| 南开区| 汝州市| 苏尼特左旗| 临夏市| 福建省| 松桃| 长白| 大荔县| 宜阳县| 酉阳| 红河县| 会昌县| 塔河县| 张掖市| 闻喜县| 扬州市| 永登县| 西平县| 景泰县| 通河县| 芦山县| 神池县| 桦南县| 南丰县| 喜德县| 大城县| 六安市| 岳普湖县| 吴江市| 张家港市| 宁化县| 岳池县| 平南县| 汉阴县| 广元市| 和田县| 望谟县| 龙江县| 犍为县|