锁的使用至关重要
Condition成为条件队列或条件变量,为一个线程挂起执行(等待)提供了一种方法,直到另一线程通知某些状态条件现在可能为真为止。由于对该共享状态信息的访问发生在不同的线程中,因此必须由互斥锁对其其进行保护。 await方法:必须在获取锁之后的调用,表示释放当前锁,阻塞当前线程;等待其他线程调用锁的signal或signalAll方法,线程唤醒重新获取锁。 Lock配合Condition,可以实现synchronized 与 对象(wait,notify)同样的效果,来进行线程间基于共享变量的通信。但优势在于同一个锁可以由多个条件队列,当某个条件满足时,只需要唤醒对应的条件队列即可,避免无效的竞争。 // 此类实现类似阻塞队列(ArrayBlockingQueue) 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(); } } } BlockingQueue(编辑:ASP站长) 【免责声明】本站内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。 |
-
无相关信息