问题描述
我正在阅读 java.util.concurrent.locks.condition 中的 condition.
i am reading about condition in java.util.concurrent.locks.condition .
条件因素将对象监视器方法(等待、通知和通知所有)>分解为不同的对象,以产生具有多个的效果每个对象的等待集,通过将它们与任意锁的使用结合起来实现.
condition factors out the object monitor methods (wait, notify and notifyall) >into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary lock implementations.
有人可以解释一下吗?
与普通同步块或方法相比,这有什么好处?
how this is a benefit over normal synchronization blocks or method?
推荐答案
一个锁可以关联多个条件.锁是一个对象",每个条件都是一个等待集".这允许**条件共享临界区.例如,考虑有界生产者-消费者问题.解决它的一种方法是拥有一个保护队列的锁和两个**的等待集:一个用于生产者,等待槽将项目放入队列,另一个用于等待项目获取的消费者.使用普通的旧 synchronized 和 wait/notify api,我们能做的最好的事情就是遵循以下原则:
one lock can be associated with many conditions. lock is an "object", each condition is a "waiting set". this allows for independent conditions sharing critical section. for example, consider bounded producers-consumers problem. one way to solve it is to have one lock that protects the queue, and two independent waiting sets: one for producers, waiting for slot to place item in the queue, other for consumers waiting for items to take. using plain old synchronized and wait/notify api, best we can do is along these lines:
制作人:
producer:
synchronized (lock) { while (queue.isfull()) { lock.wait(); } queue.put(sth); lock.notify(); }
消费者:
consumer:
synchronized (lock) { while (queue.isempty() { lock.wait(); } product = queue.take(); lock.notify(); }
这样做的缺点是在队列的每次更改时都会唤醒生产者和消费者,即使它不可能允许给定线程继续进行(例如,当其他消费者从队列).使用 lock/condition api,我们可以实现分离等待消费者和生产者的百家乐凯发k8的解决方案,从而减少冗余唤醒和检查:
this has the disadvantage of waking up both producers and consumers on every change to the queue, even if it cannot possibly allow given thread to proceed (e.g. consumer is awoken when some other consumer takes item from the queue). using lock/condition api we can implement solution that separates waiting consumers and producers, and hence reduce redundant wakeups and checking:
lock lock = new reentrantlock(); condition hasplace = lock.newcondition(); condition hasitems = lock.newcondition();
制作人:
producer:
lock.lock(); try { while (queue.isfull()) { hasplace.await(); } queue.put(sth); hasitems.signal(); } finally { lock.unlock(); }
消费者:
consumer:
lock.lock(); try { while (queue.isempty()) { hasitems.await(); } product = queue.take(); hasplace.signal(); } finally { lock.unlock(); }
这样,消费者等待生产者生产一些项目(hasitems 条件),并在从队列中删除项目时通知生产者有一个空槽(hasplace 条件).这两个条件都与同一个临界区(锁定)相关联,因此我们保持了通常的排除和等待时释放锁的保证,同时获得了分离等待队列的能力.
this way, consumer waits for producers to produce some item (hasitems condition), and upon removing an item from the queue it notifies producers that there is an empty slot (hasplace condition). both conditions are associated with the same critical section (lock), so we keep the usual exclusion and release-lock-while-waiting guarantees, while gaining the ability to separate waiting queues.