两者区别:
公平锁,在并发环境中,每个线程在获取锁时会先查看此锁维护的等待队列,若为空,或者当前线程是等待队列的第一个,就占有锁,否则就加入到等待队列中,以后会按照FIFO的规则从队列中取到自己非公平锁,比较粗鲁,上来就直接尝试占有锁,如果尝试失败,就再用类似公平锁的方式。非公平锁优点是吞吐量比较大。也就是说:公平锁讲究的是先来后到,而非公平锁讲究的是弱肉强食。
ReentrantLock:根据构造函数的参数指定是公平锁还是非公平锁,无参构造默认是非公平锁。
/** * Creates an instance of {@code ReentrantLock}. * This is equivalent to using {@code ReentrantLock(false)}. */ public ReentrantLock() { sync = new NonfairSync(); } /** * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }Synchronized 也是一种非公平锁。
指的是同一线程外层函数获得锁之后,内层递归函数仍然能获得该锁的代码。即,线程可以获得任何一个它已经拥有的锁 所同步着的代码块。
ReentrantLock和Synchronized 就是可重入锁。可重入锁的最大作用就是可以避免死锁。
自旋锁:指的是尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。
就像之前文章中讲的CAS。
//unsafe.getAndAddInt public final int getAndAddInt(Object var1,long var2,int var4){ int var5; do{ var5 = this.getIntVolatile(var1,var2); } while(!this.compareAndSwapInt(var1,var2,var5,var5 + var4)); return var5; }下面举一个对缓存读写操作的栗子
class MyCache { private Map<String, String> map = new HashMap<>(); public void get(String key) { System.out.println(Thread.currentThread().getName() + "\t 正在读取..."); String result = map.get(key); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "读取完成:" + result); } public void set(String key, String value) { System.out.println(Thread.currentThread().getName()+"\t 正在写入..."+ key); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } map.put(key,value); System.out.println(Thread.currentThread().getName()+"\t 写入完成!"); } } public class ReentrantReadWriteLockDemo { public static void main(String[] args) { final MyCache cache = new MyCache(); for (int i = 1; i <= 5; i++) { final int finalI = i; new Thread(new Runnable() { @Override public void run() { cache.set(finalI +"", finalI +""); } },String.valueOf(i)).start(); } for (int i = 1; i <= 5; i++) { final int finalI = i; new Thread(new Runnable() { @Override public void run() { cache.get(finalI +""); } },String.valueOf(i)).start(); } } } - 打印结果- - - -- - - - -- - 1 正在写入...1 2 正在写入...2 5 正在写入...5 4 正在写入...4 3 正在写入...3 1 正在读取... 2 正在读取... 3 正在读取... 4 正在读取... 5 正在读取... 1 写入完成! 2 写入完成! 5 写入完成! 3 读取完成:null 1 读取完成:null 2 读取完成:2 4 读取完成:null 5 读取完成:5 3 写入完成! 4 写入完成!以上代码可见在没有任何措施的情况下,打印结果不堪入目,还没写完,就开始读,也就是在写的过程中,被读操作插队 了,所以导致了读取数据为null。
下面加入读写锁
class MyCache { private Map<String, String> map = new HashMap<>(); private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public void get(String key) { lock.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + "\t 正在读取..."); Thread.sleep(1000); String result = map.get(key); System.out.println(Thread.currentThread().getName() + "\t 读取完成:" + result); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.readLock().unlock(); } } public void set(String key, String value) { lock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"\t 正在写入..."+ key); Thread.sleep(1000); map.put(key,value); System.out.println(Thread.currentThread().getName()+"\t 写入完成!"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.writeLock().unlock(); } } } public class ReentrantReadWriteLockDemo { public static void main(String[] args) { final MyCache cache = new MyCache(); for (int i = 1; i <= 5; i++) { final int finalI = i; new Thread(new Runnable() { @Override public void run() { cache.set(finalI +"", finalI +""); } },String.valueOf(i)).start(); } for (int i = 1; i <= 5; i++) { final int finalI = i; new Thread(new Runnable() { @Override public void run() { cache.get(finalI +""); } },String.valueOf(i)).start(); } } } ---打印结果-------- 1 正在写入...1 1 写入完成! 3 正在写入...3 3 写入完成! 2 正在写入...2 2 写入完成! 4 正在写入...4 4 写入完成! 5 正在写入...5 5 写入完成! 1 正在读取... 2 正在读取... 3 正在读取... 4 正在读取... 5 正在读取... 1 读取完成:1 3 读取完成:3 5 读取完成:5 2 读取完成:2 4 读取完成:4加入ReentrantReadWriteLock,在写入时使用其写锁:WriteLock,在读取时使用读锁:ReadLock,从打印结果来看,写入操作没有被其他操作加塞,是一气呵成的,具有原子性。这样读写分离既保证了数据的一致性,又提升了数据并发性。
另外要注意:ReentrantReadWriteLock 和 ReentrantLock 不是继承关系,但都是基于 AbstractQueuedSynchronizer 来实现。
小结:虽然说了这么多种锁,但实际实现好多都是重复的,比如:
ReentrantLock 既是公平和非公平锁,又是可重入锁,还是独占锁Synchronized 既是非公平锁,又是可重入锁,还是独占锁