首页 / JAVA / Java多线程--公平锁与非公平锁
Java多线程--公平锁与非公平锁
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java多线程--公平锁与非公平锁,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2459字,纯文字阅读大概需要4分钟。
内容图文
上一篇文章介绍了AQS的基本原理,它其实就是一个并发包的基础组件,用来实现各种锁,各种同步组件的。它包含了state变量、加锁线程、等待队列等并发中的核心组件,现在我们来看一下多线程获取锁的顺序问题。
1 /** 2 * Creates an instance of { @code ReentrantLock}. 3 * This is equivalent to using { @code ReentrantLock(false)}. 4 */ 5 public ReentrantLock() { 6 sync = new NonfairSync(); 7 } 8 9/**10 * Creates an instance of {@code ReentrantLock} with the 11 * given fairness policy. 12 * 13 * @param fair {@code true} if this lock should use a fair ordering policy 14*/15public ReentrantLock(boolean fair) { 16 sync = fair ? new FairSync() : new NonfairSync(); 17 }
ReentrantLock有两个构造参数,一个有参,一个无参,默认的无参相当于有参数的false。
1 /** 2 * Performs non-fair tryLock. tryAcquire is implemented in 3 * subclasses, but both need nonfair try for trylock method. 4 */ 5 final boolean nonfairTryAcquire(int acquires) { 6final Thread current = Thread.currentThread(); 7int c = getState(); 8if (c == 0) { 9if (compareAndSetState(0, acquires)) { 10 setExclusiveOwnerThread(current); 11returntrue; 12 } 13 } 14elseif (current == getExclusiveOwnerThread()) { 15int nextc = c + acquires; 16if (nextc < 0) // overflow17thrownew Error("Maximum lock count exceeded"); 18 setState(nextc); 19returntrue; 20 } 21returnfalse; 22 }
如果为参数为false为非公平锁,非公平锁获取锁的方式为如果当前没有线程占有锁,当前线程直接通过cas指令占有锁,管他等待队列,就算自己排在队尾也是这样
1 /** 2 * Fair version of tryAcquire. Don‘t grant access unless 3 * recursive call or no waiters or is first. 4 */ 5 protected final boolean tryAcquire(int acquires) { 6final Thread current = Thread.currentThread(); 7int c = getState(); 8if (c == 0) { 9if (!hasQueuedPredecessors() && 10 compareAndSetState(0, acquires)) { 11 setExclusiveOwnerThread(current); 12returntrue; 13 } 14 } 15elseif (current == getExclusiveOwnerThread()) { 16int nextc = c + acquires; 17if (nextc < 0) 18thrownew Error("Maximum lock count exceeded"); 19 setState(nextc); 20returntrue; 21 } 22returnfalse; 23 }
1 public final boolean hasQueuedPredecessors() { 2 // The correctness of this depends on head being initialized 3 // before tail and on head.next being accurate if the current 4 // thread is first in queue. 5 Node t = tail; // Read fields in reverse initialization order 6 Node h = head; 7 Node s; 8return h != t && 9 ((s = h.next) == null || s.thread != Thread.currentThread()); 10 }
如果为参数为true为公平锁,公平锁获取锁的方式为如果当前线程是等待队列的第一个或者等待队列为空或为当前占有线程,则通过cas指令设置state为1或增加。公平锁加锁的线程全部是按照先来后到的顺序,依次进入等待队列中排队的,不会盲目的胡乱抢占加锁。
原文:https://www.cnblogs.com/ding-dang/p/11145404.html
内容总结
以上是互联网集市为您收集整理的Java多线程--公平锁与非公平锁全部内容,希望文章能够帮你解决Java多线程--公平锁与非公平锁所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。