当前位置:首页 > 开发 > 编程语言 > 持续集成 > 正文

ReentrantLock的条件锁Condition用法

发表于: 2013-06-20   作者:aigo   来源:转载   浏览次数:
摘要: 原文:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html 这个例子很好的解释了ReentrantLock的条件锁-Condition的用法:   看完API文档中这个例子后,我很疑惑:如果线程A进入了take方法,并拿到了Lock的拥有权,同事阻塞在了await

原文:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html

这个例子很好的解释了ReentrantLock的条件锁-Condition的用法:

 

看完API文档中这个例子后,我很疑惑:如果线程A进入了take方法,并拿到了Lock的拥有权,同事阻塞在了await()方法处,此时线程B进入了put方法,线程B试图去获取Lock的拥有权,但之前线程A还没释放锁,岂不是线程B无法走到put方法的signal()处,这样就不造成线程死锁了吗!

这篇文章给了一个很好的解释:
Both Lock and synchronized temporarily allow others to obtain the lock when they are waiting. To stop waiting, a thread have to re-acquire the lock.

http://stackoverflow.com/questions/12578687/waiting-on-a-condition-in-a-reentrant-lock

 

原来Condtion.await()的时候线程A会允许其他线程来抢夺锁,当线程A的阻塞状态被唤醒后,线程A会重新去抢夺锁。

 

public interface Condition

Condition factors out the Object monitor methods (waitnotify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lockimplementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.

Conditions (also known as condition queues or condition variables) provide a means for one thread to suspend execution (to "wait") until notified by another thread that some state condition may now be true. Because access to this shared state information occurs in different threads, it must be protected, so a lock of some form is associated with the condition. The key property that waiting for a condition provides is that it atomicallyreleases the associated lock and suspends the current thread, just like Object.wait.

Condition instance is intrinsically bound to a lock. To obtain a Condition instance for a particular Lock instance use its newCondition() method.

As an example, suppose we have a bounded buffer which supports put and take methods. If a take is attempted on an empty buffer, then the thread will block until an item becomes available; if a put is attempted on a full buffer, then the thread will block until a space becomes available. We would like to keep waiting put threads and take threads in separate wait-sets so that we can use the optimization of only notifying a single thread at a time when items or spaces become available in the buffer. This can be achieved using two Condition instances.

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

(The ArrayBlockingQueue class provides this functionality, so there is no reason to implement this sample usage class.)

Condition implementation can provide behavior and semantics that is different from that of the Object monitor methods, such as guaranteed ordering for notifications, or not requiring a lock to be held when performing notifications. If an implementation provides such specialized semantics then the implementation must document those semantics.

Note that Condition instances are just normal objects and can themselves be used as the target in a synchronized statement, and can have their own monitor wait and notification methods invoked. Acquiring the monitor lock of a Condition instance, or using its monitor methods, has no specified relationship with acquiring the Lock associated with that Condition or the use of its waiting and signalling methods. It is recommended that to avoid confusion you never use Condition instances in this way, except perhaps within their own implementation.

Except where noted, passing a null value for any parameter will result in a NullPointerException being thrown.

Implementation Considerations

When waiting upon a Condition, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a Conditionshould always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop.

The three forms of condition waiting (interruptible, non-interruptible, and timed) may differ in their ease of implementation on some platforms and in their performance characteristics. In particular, it may be difficult to provide these features and maintain specific semantics such as ordering guarantees. Further, the ability to interrupt the actual suspension of the thread may not always be feasible to implement on all platforms.

Consequently, an implementation is not required to define exactly the same guarantees or semantics for all three forms of waiting, nor is it required to support interruption of the actual suspension of the thread.

An implementation is required to clearly document the semantics and guarantees provided by each of the waiting methods, and when an implementation does support interruption of thread suspension then it must obey the interruption semantics as defined in this interface.

As interruption generally implies cancellation, and checks for interruption are often infrequent, an implementation can favor responding to an interrupt over normal method return. This is true even if it can be shown that the interrupt occurred after another action may have unblocked the thread. An implementation should document this behavior.

ReentrantLock的条件锁Condition用法

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
推荐 : ReentrantLock与synchronized 1. 什么是可重入锁? - “就是可以重新获得锁!”可重入的意
1.条件变量和mutex到底有什么区别?都是在没有拿锁的情况下阻塞,拿到锁了解除阻塞。那为什么还要用
  为了允许在线程或进程之间共享数据,同步时必须的,互斥锁和条件变量是同步的基本组成部分。 1
ReentrantLock 是一个可重入的锁,用于线程之间的同步。 采用独占锁方式,即一个线程获得锁,其它线
一、前言 ReentrantLock是JDK1.5引入的,它拥有与synchronized相同的并发性和内存语义,并提供了超
业务背景: 系统启动时需要向DRM服务器注册资源,同一个资源只能注册一次,不能重复注册。现在有两
Condition是Locks锁下的还有一种线程通信之间唤醒、堵塞的实现。它以下的await,和signal可以实现Obj
Java5 中提过了Condition ,该类可以实现线程间的条件控制,废话少说直接来看一个实例。 实例: 启
MySQL5.6.7-rc index condition pushdown 索引条件下推代码解读 http://jishu.zol.com.cn/4505.html
接着上一篇的 关于java线程(4)----JUC之 AQS 状态依赖的抽象 看一下ReentrantLock的源码,这里只是
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号