ReentrantLock与AQS
synchronized和ReentrantLock的区别
先说说synchronized和ReentrantLock的区别吧,AQS的分析得等两天了:
1、ReentrantLock (再入锁),位于java.util.concurrent.locks包 2、和CountDownLatch、Future Task、Semaphore一样基于AQS实现 3、能够实现比synchronized更细粒度的控制,如控制公平与非公平 4、调用lock()之后,必须调用unlock()释放锁 5、性能未必比synchronized高,并且也是可重入的 6、synchronized是关键字,ReentrantLock是类 7、ReentrantLock可以对获取锁的等待时间进行设置,避免死锁的发生 8、ReentrantLock可以获取各种锁的信息 9、ReentrantLock可以灵活地实现多路通知 10、机制:sync操作Mark Word,lock调用Unsafe类的park()方法
关于ReentrantLock公平性的设置
ReentrantLock fairLock = new ReentrantLock(true);
1、参数为true时,倾向于将锁赋予等待时间最久的线程
2、公平锁:获取锁的顺序按先后调用lock方法的顺序(慎用)
3、非公平锁:抢占的顺序不一定,看运气
4、synchronized是非公平锁,如果比较强调吞吐量,没必要设置为公平锁
1import java.util.concurrent.locks.ReentrantLock;
2
3public class ReentrantLockDemo implements Runnable{
4 private static ReentrantLock reentrantLock = new ReentrantLock(true);
5
6 @Override
7 public void run() {
8 while (true){
9 try {
10 reentrantLock.lock();
11 System.out.println(Thread.currentThread().getName() + " get lock");
12 Thread.sleep(1000);
13 } catch (InterruptedException e) {
14 e.printStackTrace();
15 }finally {
16 reentrantLock.unlock();
17 }
18 }
19 }
20
21 public static void main(String[] args) {
22 ReentrantLockDemo lockDemo = new ReentrantLockDemo();
23 Thread thread1 = new Thread(lockDemo, "Thread1");
24 Thread thread2 = new Thread(lockDemo, "Thread2");
25 thread1.start();
26 thread2.start();
27 }
28}