当前位置: 首页 > news >正文

上海洛可可设计公司网站设计 网站开发 优化

上海洛可可设计公司,网站设计 网站开发 优化,门户网站模板下载,谁给推荐一个免费的好网站前言 多线程知识中理解了ReentrantLock之后#xff0c;对于整个AQS也会有大概的理解#xff0c;后面再去看其它锁的源码就会比较容易。下面带大家一块来学习ReentrantLock源码。 概述 ReentrantLock是可重入的互斥锁#xff0c;虽然具有与synchronized相同功能#xff0…前言 多线程知识中理解了ReentrantLock之后对于整个AQS也会有大概的理解后面再去看其它锁的源码就会比较容易。下面带大家一块来学习ReentrantLock源码。 概述 ReentrantLock是可重入的互斥锁虽然具有与synchronized相同功能但是会比synchronized更加灵活具有更多的方法。ReentrantLock底层基于AbstractQueuedSynchronized。有两种锁方式公平锁和非公平锁公平锁指线程锁定后会进入队列进行排队等待至获得锁的使用权而非公平锁指线程锁定后会尝试获取锁如果获取失败则进入等待队列进行排队。 正文 应用场景 下面有这么一段代码有10个线程对count进行累加每个线程累加10000次那么最终期望的输出值肯定是100000。 private static int count 0;private static void inrc() {count;}public static void main(String[] args) throws InterruptedException {for (int i 0; i 10; i) {new Thread(() - {for (int a0;a10000;a){inrc();}}).start();}TimeUnit.SECONDS.sleep(3);System.out.println(count);} 不加锁的情况输出会不符合我们的预期。 使用ReentrantLock加锁。 private static Lock lock new ReentrantLock();private static int count 0;private static void inrc() {try {//加锁lock.lock();count;} catch (Exception e) {e.printStackTrace();}finally {lock.unlock();}}public static void main(String[] args) throws InterruptedException {for (int i 0; i 10; i) {new Thread(() - {for (int a0;a10000;a){inrc();}}).start();}TimeUnit.SECONDS.sleep(3);System.out.println(count);}输出结果符合预期 NonfairSynclock方法 ReentrantLock默认为非公平锁从其构造方式中可以看出。 public ReentrantLock() {sync new NonfairSync();}下面我们来追踪ReentrantLock的lock()方法由于默认为非公平锁所以当我们调用lock方法时实际调用的是NonfairSync的lock方法 public void lock() {sync.lock();}final void lock() {//尝试通过CAS修改state值如果此时成功的修改了state的值为1则证明竞争到了锁资源if (compareAndSetState(0, 1))//将线程占用者属性设置为当前线程setExclusiveOwnerThread(Thread.currentThread());else//如果占用失败则再次尝试如果还失败则会加入队列进行等待acquire(1);} 由于是非公平锁所以进入该方法时会先尝试获取锁资源通过CAS可以保证原子性即线程安全设置state值为1如果成功设置则是拿到了资源否则调用acquire方法进行尝试。如果是公平锁的话直接调用acquire()方法 AQSacquire方法 public final void acquire(int arg) {//tryAcquire(arg):再次尝试获取锁资源//addWaiter(Node.EXCLUSIVE)前面的判断如果获取不到锁资源则将添加当前线程到队列中进行等待//acquireQueued自旋尝试获取锁资源//selfInterrupt()如果当前线程的状态被打断了则将当前线程打断掉只有当前线程有权限打断自己所在线程if (!tryAcquire(arg) acquireQueued(addWaiter(Node.EXCLUSIVE), arg))selfInterrupt();}1、tryAcquire(arg)这里会再次尝试是否能获取到锁资源有可能当前拥有锁资源的线程就是自己所在的线程那么这时候是支持锁重入的。 2、acquireQueued(addWaiter(Node.EXCLUSIVE), arg))添加当前线程到队列中并以自旋的方式尝试获取锁资源。 3、selfInterrupt()当前线程的状态如果为打断状态则将当前线程打断掉只有当前线程有权限打断自己所在线程 NonfairSync tryAcquire方法 protected final boolean tryAcquire(int acquires) {return nonfairTryAcquire(acquires);}final boolean nonfairTryAcquire(int acquires) {//获取当前线程final Thread current Thread.currentThread();//获取state的状态看是否被占有int c getState();//如果为0则代表当前为被占有if (c 0) {//通过CAS方式尝试修改其值进行资源占用if (compareAndSetState(0, acquires)) {//成功则将当前线程为资源拥有者setExclusiveOwnerThread(current);return true;}}//判断资源拥有者与当前线程是否是同个如果是则将state值进行累加达到可重入的目的else if (current getExclusiveOwnerThread()) {int nextc c acquires;if (nextc 0) // overflowthrow new Error(Maximum lock count exceeded);setState(nextc);return true;}return false;}AQSaddWaiter方法 AQS中的队列结构为双向链表结构每个节点为node对象该对象拥有前置节点、后置节点属性 private Node addWaiter(Node mode) {//将当前线程封装成nodeNode node new Node(Thread.currentThread(), mode);// Try the fast path of enq; backup to full enq on failure//判断链表的尾部节点是否为空如果为空则证明整个队列没有值Node pred tail;if (pred ! null) {//设置当前节点的前置节点node.prev pred;//通过CAS的方式将当前节点与上个节点关联起来。通过CAS保证线程安全if (compareAndSetTail(pred, node)) {pred.next node;return node;}}enq(node);return node;}AQS acquireQueued方法 final boolean acquireQueued(final Node node, int arg) {boolean failed true;try {boolean interrupted false;//死循环for (;;) {//获取当前线程节点在队列中的前一个线程节点final Node p node.predecessor();//判断其是否处于队列头部位置如果是则代表快轮到自己了进行尝试获取资源if (p head tryAcquire(arg)) {setHead(node);p.next null; // help GCfailed false;return interrupted;}//判断当前线程的状态是否为等待中如果是则返回true不是则将状态设置为等待状态if (shouldParkAfterFailedAcquire(p, node) //阻塞并返回当前线程是否被打断标识parkAndCheckInterrupt())interrupted true;}} finally {if (failed)cancelAcquire(node);}}AQSshouldParkAfterFailedAcquire方法 private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {int ws pred.waitStatus;//如果上个节点处于等待状态则代表当前的线程可以进行阻塞因为上个线程都没获取资源肯定不会轮到自己的可以安心阻塞if (ws Node.SIGNAL)/** This node has already set status asking a release* to signal it, so it can safely park.*/return true;//状态大于0证明上个线程取消了需要从队列中往前查一个未取消的if (ws 0) {/** Predecessor was cancelled. Skip over predecessors and* indicate retry.*/do {node.prev pred pred.prev;} while (pred.waitStatus 0);pred.next node;} else {/** waitStatus must be 0 or PROPAGATE. Indicate that we* need a signal, but dont park yet. Caller will need to* retry to make sure it cannot acquire before parking.*///将当前节点设置为等待状态compareAndSetWaitStatus(pred, ws, Node.SIGNAL);}return false;}AQSparkAndCheckInterrupt private final boolean parkAndCheckInterrupt() {LockSupport.park(this);return Thread.interrupted();}public static void park(Object blocker) {Thread t Thread.currentThread();setBlocker(t, blocker);//调用park方法进行阻塞这样调用的是native方法即调用内核态库中的函数UNSAFE.park(false, 0L);setBlocker(t, null);}AQScancelAcquire方法 private void cancelAcquire(Node node) {// Ignore if node doesnt existif (node null)return;//将当前线程置为null方便gcnode.thread null;// Skip cancelled predecessors//获取上个节点Node pred node.prev;while (pred.waitStatus 0)node.prev pred pred.prev;// predNext is the apparent node to unsplice. CASes below will// fail if not, in which case, we lost race vs another cancel// or signal, so no further action is necessary.Node predNext pred.next;// Can use unconditional write instead of CAS here.// After this atomic step, other Nodes can skip past us.// Before, we are free of interference from other threads.//将线程状态设置为取消node.waitStatus Node.CANCELLED;// If we are the tail, remove ourselves.//如果当前线程位于队列的最后一个位置由于取消了所以要将上个队列位置的线程置为尾部if (node tail compareAndSetTail(node, pred)) {compareAndSetNext(pred, predNext, null);} else {// If successor needs signal, try to set preds next-link// so it will get one. Otherwise wake it up to propagate.int ws;//这一步只要将上个线程与下个线程进行关联移除当前线程在队列的位置if (pred ! head ((ws pred.waitStatus) Node.SIGNAL ||(ws 0 compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) pred.thread ! null) {Node next node.next;if (next ! null next.waitStatus 0)compareAndSetNext(pred, predNext, next);} else {//释放下一个线程阻塞状态unparkSuccessor(node);}node.next node; // help GC}}AQSunparkSuccessor private void unparkSuccessor(Node node) {/** If status is negative (i.e., possibly needing signal) try* to clear in anticipation of signalling. It is OK if this* fails or if status is changed by waiting thread.*/int ws node.waitStatus;if (ws 0)compareAndSetWaitStatus(node, ws, 0);/** Thread to unpark is held in successor, which is normally* just the next node. But if cancelled or apparently null,* traverse backwards from tail to find the actual* non-cancelled successor.*/Node s node.next;if (s null || s.waitStatus 0) {s null;for (Node t tail; t ! null t ! node; t t.prev)if (t.waitStatus 0)s t;}if (s ! null)//释放线程的阻塞状态LockSupport.unpark(s.thread);} NonfairSyncunlock方法 通过前面的步骤我们知道处于队列中的线程都处于阻塞状态持有资源的线程执行完之后需要调用unlock方法将队列中的下一个线程唤醒并将自己从队列中进行移除。 public void unlock() {sync.release(1);}AQSrelease方法 public final boolean release(int arg) {//判断是否能释放因为ReentrantLock是重入锁每次重入时state会加1所以如果state-1不等于0的话需要多次的unlock才能达到释放资源。比如同个线程中调用了两次lock需要调用两次unlock才能释放资源。if (tryRelease(arg)) {Node h head;if (h ! null h.waitStatus ! 0)//将下个节点唤醒unparkSuccessor(h);return true;}return false;}ReentrantLocktryRelease方法 protected final boolean tryRelease(int releases) {//将state减一int c getState() - releases;if (Thread.currentThread() ! getExclusiveOwnerThread())throw new IllegalMonitorStateException();boolean free false;//如果为0释放资源if (c 0) {free true;setExclusiveOwnerThread(null);}//不为0证明之前有过重入的情况需要等该线程的所有unlock方法执行完毕后state等于0才能释放setState(c);return free;}AQSunparkSuccessor方法 private void unparkSuccessor(Node node) {/** If status is negative (i.e., possibly needing signal) try* to clear in anticipation of signalling. It is OK if this* fails or if status is changed by waiting thread.*/int ws node.waitStatus;//将当前线程状态设置为0if (ws 0)compareAndSetWaitStatus(node, ws, 0);/** Thread to unpark is held in successor, which is normally* just the next node. But if cancelled or apparently null,* traverse backwards from tail to find the actual* non-cancelled successor.*///查找下个节点状态不为取消的Node s node.next;if (s null || s.waitStatus 0) {s null;for (Node t tail; t ! null t ! node; t t.prev)if (t.waitStatus 0)s t;}if (s ! null)//唤醒LockSupport.unpark(s.thread);}总结 下面画了流程图帮助大家更好的理解。 非公平锁 公平锁 解锁
http://www.w-s-a.com/news/35889/

相关文章:

  • 营销软件网站wordpress优秀的破解主题
  • 卧龙区网站建设国内漂亮网站欣赏
  • 服装 网站模板 wordpress石家庄做网站的公司有哪些
  • 惠州技术支持网站建设百度怎样注册免费的网站
  • 无锡哪里有做网站的公司泸州网站建设公司
  • 怎么进行网站推广jsp可以做那些小网站
  • 懒人手机网站wordpress修改秒速
  • WordPress资讯网站用花生壳做网站
  • 关于营销方面的网站建设网站怎么克隆
  • 站长网seo综合查询工具电商公司简介
  • 全能网站建设教程广告制作公司需要什么设备
  • 汽车行业做网站网站改版seo建议
  • 建设职业注册中心网站photoshop属于什么软件
  • 公司网站展示有哪些wordpress工单
  • iis新建网站seo是做什么工作的
  • 临沂网站建设厂家做外贸的女生现状
  • 电子商务网站建设实践临沂做网站的
  • 网站职能建设论文做外贸都有哪些网站
  • 网站建设项目需求分析房地产网站源码
  • 网站充值提现公司账务怎么做中国能建设计公司网站
  • 网站信息资源建设包括哪些网站网站做维护
  • 网站性能优化的方法有哪些建设施工合同网站
  • 郑州建设企业网站山西省住房和城乡建设厅网站
  • 做网站的去哪找客户正规制作网站公司
  • 网站代理访问是什么意思外国优秀设计网站
  • 合肥个人建站模板网络技术服务有限公司
  • 做网站什么公司好dw企业网站开发教程
  • 怎么做自己的个人网站宝安网站设计哪家最好
  • 浩博建设集团网站站长网站统计
  • 电商网站开发视频seo排名优化方式方法