Condition give the effect of having multiple wait-sets per object?

后端 未结 3 483
悲哀的现实
悲哀的现实 2021-01-07 10:28

I am reading about Condition in java.util.concurrent.locks.Condition .

Condition factors out the Object monitor methods (wait, notify and

3条回答
  •  难免孤独
    2021-01-07 10:47

    Previously before the Explicit Locks we used Object wait() and notify() methods for making threads to wait until some event occurred and then triggering them using notify() and the mutex of that Object must be with the thread calling these methods.

    So there was only one wait-set per lock object. Wait set is the set where the threads that call wait() on the object are stored (not literraly).

    But with the Explicit Lock framework using a single lock you can create multiple wait-sets for different conditions that are related to the same lock. As the example in Javadoc also explain the same fact.

    Multiple Conditions == Multiple Wait sets
    
     final Lock lock = new ReentrantLock(); //Single Lock
     final Condition notFull  = lock.newCondition(); //Multiple conditions
     final Condition notEmpty = lock.newCondition();
    

    So as in the case of Buffer example from JavaDoc consumer threads will wait on the condition for the Buffer to be NOT EMPTY and the producer threads will wait on the condition NOT FULL.

提交回复
热议问题