ReentrantLock可重入锁 ReentrantLock为例实现细节 juc.Condition

aqs(AbstractQueuedSynchronizer)是一个用于构建锁和同步器的框架
java.util.concurrent包中ReentrantLock、Semaphore、CountDownLatch、ReentrantReadWriteLock、SynchronousQueue都是通过aqs实现的

ReentrantLock为例实现细节

ReentrantLock.lock()

public void lock() {
    sync.lock();
}

ReentrantLock.NonfairSync.lock()

final void lock() {
    //第一个线程通过cas修改state状态,0->1。修改成功返回true
    if (compareAndSetState(0, 1))
        setExclusiveOwnerThread(Thread.currentThread());    //记录当前独占线程
    else
        acquire(1); //如果没有获取到锁,调用AQS.acquire(1);
}

AQS.acquire(1);

public final void acquire(int arg) {
    //tryAcquire是aqs的模板方法,如果使用的非公平锁ReentrantLock.NonfairSync会重写这个方法
    if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

ReentrantLock.NonfairSync.tryAcquire()

protected final boolean tryAcquire(int acquires) {
    return nonfairTryAcquire(acquires);
}

//此方法在NonfairSync父类Sync中
final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    //如果状态state被其他线程释放后,修改为0。那么此时当前线程就可以直接拿到执行权,并返回true。AQS.acquire也就没有必要在将线程放入锁池中了。
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    } 
    //如果state<>0那么说明锁被其他线程占有,还没有释放。但是要判断一下是不是线程自己占有的。如果是当前线程,那么将state+1b,返回true。AQS.acquire也就没有必要在将线程放入锁池中了。
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            //这个异常导致的原因待分析.............
            throw new Error("Maximum lock count exceeded"); 
        setState(nextc);
        return true;
    }
    //如果既没有拿到执行权又不是当前线程重入,那么就说明锁已被其他线程占用,返回false。继续执行AQS.acquire方法中的 acquireQueued方法,将当前线程挂起放入锁池中
    return false;
}

acquireQueued(addWaiter(Node.EXCLUSIVE), arg)

//线程没有获取到state锁状态,就需要放入到一个锁池中(aqs中链表),然后在将这个线程挂起等待唤醒。
private Node addWaiter(Node mode) {
    Node node = new Node(Thread.currentThread(), mode);
    Node pred = tail;
    if (pred != null) {
        //如果aqs队列存在尾节点,那么就把新的node节点的前节点执行tail
        //         tail <- node 相当于
        node.prev = pred;
        //这一步cas操作是把aqs.tail 换成新加入链表的 node节点
        //         node(原tail对象) <- aqs.tail(新node节点对象)
        if (compareAndSetTail(pred, node)) {
            //这一步相当于把原tail对象的next指向 新node节点
            //     node(原tail对象).next -> aqs.tail(新node节点对象)
            pred.next = node;
            return node;
        }
    }
    //如果一共三个线程,那么第一个线程不会进入到这个addWaiter方法,第二个线程会进入enq方法,将当前线程封装的node节点放入队列,head与tail相同。当第三个线程就会满足if(pred != null)逻辑。
    enq(node); 
    return node;
}

//将刚加入链表中node的线程挂起等待唤醒
final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        
        for (;;) {
            //1.取出node的前置节点
            final Node p = node.predecessor();
            //2.然后判断这个node的前置节点是不是aqs中的头节点,如果是头节点说明马上就到当前这个node节点了,所以需要在尝试获取一下锁状态(state)。因为在这个过程中很有可能aqs那个头节点已经release了,并且锁状态就变成0了。
            if (p == head && tryAcquire(arg)) {
                //3.如果aqs头节点释放了那么当前节点就不需要放入锁池了再挂起了。将当前节点设置为aqs头节点,然后将aqs原头结点设置成null,等GC。
                setHead(node);
                p.next = null; // help GC 
                
                failed = false;
                
                return interrupted;
            }
            //如果不符合第一个if判断,再判断是否需要挂起等待,如果需要阻塞线程。
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
        
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

自己根据理解实现自定义的锁工具

以下是根据aqs理解实现的,没有经过大量验证一定会存在无数bug,并且没有考虑锁重入,线程中断,执行效率等等问题。

aqs的主要技术:自旋+volatile+CAS、LockSupport、锁池

MyLock.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class MyLock {

    //锁状态
    AtomicInteger status = new AtomicInteger(0);
    
    //锁池(所有被阻塞的线程)
    List<Thread> threadList = Collections.synchronizedList(new ArrayList<Thread>());
    
    //上锁(获取程序执行权)
    public void lock() {
        //偏向
        if(status.compareAndSet(0, 1)) {
            return;
        }
        //轻量
        for (int i = 0; i < 10; i++) {
            if(status.compareAndSet(0, 1)) {
                return;
            }
        }
        //重量
        while(true) {
            if(status.compareAndSet(0, 1)) {    //当线程被唤醒时,需要把状态修改成占用状态
                return;
            }
            threadList.add(Thread.currentThread()); //并放入到锁池中去,等待unLock操作随机唤醒
            LockSupport.park(this); //当前线程阻塞
            
        }
        
    }
    
    //解锁(其实是解除锁池中线程的阻塞状态)
    public void unLock() {
        status.getAndSet(0);    //将锁状态修改成未占用状态
        if(!threadList.isEmpty()) {
            //随机从锁池中恢复一个线程(模拟非公平锁)
            LockSupport.unpark(threadList.remove(new Random().nextInt(threadList.size()))); 
        }
    }
}

测试类

public class Test3{
    
    static MyLock lock = new MyLock();
    
    static int count = 0;
    
    public static void main(String[] args) {
        
        CountDownLatch c = new CountDownLatch(10);
        
        for(int i=0; i<10; i++) {
            new Thread(()->{
                try {
                    TimeUnit.MILLISECONDS.sleep(1); //方便模拟出count是线程不安全的状态值
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count();
                c.countDown();
            }).start();
        }
        
        try {
            c.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println(count);
    }
    
    public static void count() {
        lock.lock();
        
        for(int i=0; i<1000; i++) {
            count++;
        }
        
        lock.unLock();
    }
}

源码中非公平锁与公平锁的区别在于tryAquire,非公平锁对于新线程会先去竞争state状态,如果竞争成功就可以执行,才不管你锁池里有没有等待的线程。如果竞争不到没办法进入锁池排队去。而公平锁对于新线程会先去判断锁池里有没有等待的线程如果有,不好意思直接进锁池排队去。
线程一旦进去了锁池那么两者就没有区别了都排着队一个一个的从头部节点释放出来。

如果非公平锁能像自己实现的那样能从锁池中随机释放线程锁去争抢执行权,从全部线程来看是不是更不公平一些。

juc.Condition

线程之间协作,比如一个阻塞队列。push方法是向队列添加值,pull方法是拉取值。阻塞队列就是如果队列没有内容pull方法阻塞直到队列有值。那么通过Condition的await、signal实现阻塞队列。

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLock_main {

    //测试阻塞队列
    public static void main(String[] args) {
        
        MyBlockingQueue<String> mb = new MyBlockingQueue<String>();
        
        //输入线程
        new Thread(()->{
            Scanner s = new Scanner(System.in); //控制台输入内容
            while(true) {
                String str = s.nextLine();
                if("exit".equals(str)) {
                    System.exit(0); //退出
                } else {
                    System.out.println("输入了:" + str);
                    mb.push(str);
                }
            }
        }).start();
    
        //接收线程A
        new Thread(()->{
            for(;;) {
                System.out.print("  乙pull " + mb.pull());
            }
        }).start();
        
        //接收线程B
        new Thread(()->{
            for(;;) {
                System.out.print("  丙pull " + mb.pull());
            }
        }).start();
    }

}

/**
 * 阻塞队列
 * 
 * @author hdx
 * @date 2020年10月16日
 */
class MyBlockingQueue<T>{
    
    private List<T> list = new LinkedList<T>();
    
    ReentrantLock reentrantLock = new ReentrantLock();
    Condition conditionA = reentrantLock.newCondition();
    
    public void push(T t) {
        reentrantLock.lock();
        try {
            list.add(t);    //添加值
            conditionA.signal();    //通知await可以执行了
        } finally {
            reentrantLock.unlock();
        }
    }
    
    public T pull() {
        reentrantLock.lock();
        try {
            while(true) {
                if(list.size() > 0) {   //如果有值就返回值
                    return list.remove(0);
                } else {
                    try {
                        conditionA.await(); //如果没有值就在此等着。
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } finally {
            reentrantLock.unlock();
        }
    }
}

conditionA.await() 与 wait相同
conditionA.signal() 与notify相同
conditionA.signalAll()与notifyAll相同

juc.Condition实现细节

await方法分析

public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();  //condition对象内部也有一个单向链表,向尾部增加节点。
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
 }

signal方法分析


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章