加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

锁的使用至关重要

发布时间:2021-05-25 13:30:04 所属栏目:编程 来源:互联网
导读:ReentrantLock 独有锁的实现,拥有上面罗列的除读写锁之外的全部特征,行使较量简朴 classX{ //建设独有锁实例 privatefinalReentrantLock lock = new Reentrant

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

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读