java多线程学习(六) 之 Condition
和synchronized一样,Lock是为了线程互斥而设计的,在synchronized中,使用对象隐式锁的wait notify(notifyAll)来实现线程之间的通信,同样的功能在Lock中是通过Codition来实现的。Condition除了完成wait和notify的基本功能之外,它的好处在于一个Lock可以通过创建多个Condition,选择性的去通知wait的线程。 官方解释: 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. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods. Condition把隐式锁的wait notify notifyAll功能提取出来,赋予确切的对象,让一个对象有个多等待集(wait-sets),这些condition也是和Lock实例绑定的,换句话说,Lock对象代替了synchronized,condition代替了wait、notify(notifyAll)等方法。 因为一个Lock可以生成多个Condition,所以condition可以让所有的因Lock等待的线程分成几个相互等待的子集合,也就是前面提到的wait-sets. 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 atomically releases the associated lock and suspends the current thread, just like Object.wait. ...