ReentrantLock深入学习

ReentrankLock  分为 非公平锁及公平锁

首先我们看一下它里面有哪些属性:

private final Sync sync;

Sync 这个类是 ReentrantLock的 一个静态内部类,实现了AbstractQueuedSynchronizer

ReentrantLock根据传入构造方法的布尔型参数实例化出Sync的实现类FairSync和NonfairSync,分别表示公平的Sync和非公平的Sync


AbstractQueuedSynchronizer这个类中封装了同步过程中堵塞的线程队列,它里面对线程之间的切换,同步的占用,做了很好的处理

像CountDownLatch、FutureTask、Semaphore、ReentrantLock等都有一个内部类是这个抽象类的子类


下面我们介绍几个ReentrantLock的核心方法及属性:
private volatile int state;


这个属性初始化为0,表示当前没有加锁,每次lock()操作,便会累加这个值,同样一个线程想要获取这个锁,做CAS操作的时候,也是判断state的值是否为0
1
2
3
4
5
6
NonfairSync锁:   final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }fairSync锁:final void lock() {    acquire(1);}

 tryAcquire方法中,先 判断当前state值是否是0,若为0 ,则可进行尝试加锁。若不为0,判断作这个加锁操作的是否为当前线程,若为当前线程,则直接累加,然后更新state值

setExclusiveOwnerThread(current)  是设置当前线程为占有线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fairSync锁:    protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
NonfairSync锁:final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

 

同样,unlock(),则会在这个值 上进行-1。从代码上看最终会调用tryRelease 方法,我们可以看到之后在state值为0的时候,才会清空当前占有线程。
当state为0时,tryRelease 返回的则是true, 则会判断head是否为null(不为空则表示有阻塞线程,这里阻塞队列这里怎么处理,可以看AbstractQueuedSynchronizer的处理,参考:http://www.cnblogs.com/xrq730/p/4979021.html)
之后,会进行unparkSuccessor()的处理,这个方法是AbstractQueuedSynchronizer的方法最终会调用LockSupport.unpark(s.thread);s.thread 为阻塞队列中的一个线程,应该是最接近head的阻塞线程(head为阻塞队列的头指针)
1
2
3
4
5
6
7
8
9
10
11
public void unlock() {
        sync.release(1);
    }public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}

 

1
2
3
4
5
6
7
8
9
10
11
12
protected final boolean tryRelease(int releases) {
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) {
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}

 

 

在看JDK源代码的时候,我们会经常的看到try开头的方法,这些方法都是无锁的方式,通过CAS进行多次尝试,会自旋式的获取锁,只有在一定时间内,仍没有获取到锁,才会进行park操作(unsafe的park操作,将线程挂起)

final Thread getOwner()
获取当前占有线程
final int getHoldCount()

获取当前的state值
public final int getQueueLength()

获取阻塞队列的长度



最后,附上简单的使用代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class ReentrantLockDemo {
 
    private static int i=0;
 
    public static void main(String[] args) throws InterruptedException {
        final ReentrantLock myLock = new ReentrantLock();
        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                for(int j=0;j<1000;j++){
                    myLock.lock();
                    i++;
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    myLock.unlock();
                }
 
            }
        });
        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                for(int j=0;j<1000;j++){
                    myLock.lock();
                    i++;
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    myLock.unlock();
                }
 
            }
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(i);
    }
}

 

 





posted @   程序员小李  阅读(339)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示