Condition是Object里面的wait、notify、notifyAll方法的一个替换Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.锁(Lock)替换了synchronized 方法和synchronized 代码块,条件(Condition)替换了Object类里面的监视器方法如:wait、notify、notifyAll
Condition的await或者signal方法必须在持有锁的时候调用,即在lock.lock()及lock.unlock()之间调用
如果当前线程没有持有锁就去调用Condition的await或者signal方法,将抛出一个IllegalMonitorStateException异常
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(); } } }await方法:进入等待状态
Causes the current thread to wait until it is signalled or interrupted.调用该方法将会使当前线程进入等待状态,知道收到signal信号或者被中断。如果一个线程进入wait状态,如下情况能够唤醒:一、其他线程调用了signal方法、并且当前线程正好被选中唤醒。二、其他线程调用了signalAll方法。三、其他线程中断了( interrupts)当前线程。四、发生了伪唤醒。不管发生上面的哪一种情况,当前线程都需要重新获取锁。
awaitNanos方法:等待指定时间
awaitUninterruptibly方法:进入等待状态,interrupt对这个等待无效,忽略中断请求
signal方法:唤醒等待线程中的其中一个
signalAll方法:唤醒所有正在等待的线程