JUC学习(七):ReentrantLock和Condition

目录

1.Condition的使用

1)await方法

2)signal、signalAll方法

2.ReentrantLock的原理

1)lock方法

2)unlock方法


初学并发时,一般都是使用synchronized关键字来保证线程安全,它具有使用方便的优点,尽管旧版本性能不佳,经过长期的优化,目前它的性能并不输给ReentrantLock。这两种锁都是可重入锁,即同一个线程再次进入同步代码时,可以使用自己已获取到的锁,从而避免重复获取锁带来的死锁问题。

synchronized和ReentrantLock的主要区别如下:

  1. synchronized是依赖于JVM实现的,而ReentrantLock是JDK实现的
  2. synchronized粒度较粗,灵活性不佳,ReentrantLock可以灵活控制加锁范围,不过需要显式加解锁
  3. ReentrantLock可以是公平锁或非公平锁,synchronized只能是非公平锁
  4. ReentrantLock可以使用lockInterruptibly建立一个可中断锁,synchronized没有这个机制
  5. ReentrantLock可以通过Condition实现线程分组唤醒,synchronized没有这个机制

下面给出一个例子:

public class ReentrantLockTest {
    static ReentrantLock lock = new ReentrantLock();

    static class MyThread extends Thread{
        @Override
        public void run() {
            lock.lock();
            System.out.println("Now:"+System.currentTimeMillis());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        }
    }

    public static void main(String args[]) {
        for(int i=0;i<5;i++){
            new MyThread().start();
        }
    }
}

输出为:

Now:1551004086212
Now:1551004087214
Now:1551004088214
Now:1551004089215
Now:1551004090215

五个子线程确实都是同步执行的。不过如果设置了死循环运行,会发现这种实现有死锁风险。

类似于Semaphore、CDL,ReentrantLock也是基于AQS的,其核心内部类也叫做Sync。

1.Condition的使用

我们对 JUC学习(一):Semaphore信号量 最后的生产者-消费者问题,使用ReentrantLock进行实现:

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerCondition {
    static Semaphore mutex = new Semaphore(10);
    static ReentrantLock lock = new ReentrantLock();
    static Condition pCondition = lock.newCondition();
    static Condition cCondition = lock.newCondition();
    static AtomicInteger count=new AtomicInteger(0);

    public static void consume(){
        try {
            mutex.acquire();
            lock.lock();
            while(count.intValue()<=0){
                cCondition.await();
            }
            System.out.println("\t\t\t消费了一件产品,剩余量:"+count.decrementAndGet());
            pCondition.signalAll();
            lock.unlock();
            mutex.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void produce(){
        try {
            mutex.acquire();
            lock.lock();
            while(count.intValue()>=10){
                pCondition.await();
            }
            System.out.println("生产了一件产品,剩余量:"+count.incrementAndGet());
            cCondition.signalAll();
            lock.unlock();
            mutex.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void main(String args[]) {
        for(int i=0;i<20;i++){
            new Thread(() -> {
                produce();
            }).start();
            new Thread(() -> {
                consume();
            }).start();
        }
    }
}

可以看到,Condition是通过lock.newCondition()创建的,并且可以创建多个。Condition的等待和唤醒由await和signalAll实现。

根据源码,实际创建的是Condition接口的实现类ConditionObject。这是AQS的一个内部类。

1)await方法

Condition有四个await系列方法,有三个是超时型,一个无参方法,这里介绍无参版本。

        public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            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);
        }

该方法创建了一个Node对象,添加到ConditionObject内部的链表(虽然AQS自称这是个队列)中,然后调用LockSupport的park方法使该线程休眠。

2)signal、signalAll方法

signal实际调用了doSignal,signalAll实际调用了doSignalAll方法:

        private void doSignal(Node first) {
            do {
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }

        private void doSignalAll(Node first) {
            lastWaiter = firstWaiter = null;
            do {
                Node next = first.nextWaiter;
                first.nextWaiter = null;
                transferForSignal(first);
                first = next;
            } while (first != null);
        }

本质都是移除链表节点,doSignal除了移除首节点外,还会把已取消等待的节点移除,doSignalAll则移除所有节点。transferForSignal方法实际调用了LockSupport的unpark方法激活线程。

2.ReentrantLock的原理

虽然ReentrantLock也是基于AQS,但是和Semaphore、CDL还是有一点不同的。下面介绍其lock和unlock方法:

1)lock方法

lock方法实际调用了AQS的acquire方法,源码如下:

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

传入的arg为1。tryAcquire方法由Sync实现,非公平版本如下:

        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;
        }

c为0时,说明当前锁未被持有,只需要标记本线程持有该锁并修改锁计数值即可;否则说明锁已经持有,假如该锁已为本线程持有,则增加计数值即可。除此之外的情况,说明本线程还不能持有锁,因此返回false。公平版本方法只是多判断了一下本线程前面是否已有线程在等待锁。

假如tryAcquire失败,就需要acquireQueued方法,让本线程进入等待队列,注意调用该方法时,实际上先调用了addWaiter入列,所以此时本线程已经在队列里了:

    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

该方法实际就是自旋地等待轮到本线程持有锁。

lock方法还有几个变体:

  • lockInterruptibly方法:实际调用acquireInterruptibly方法,原理请参见 JUC学习(一):Semaphore信号量
  • tryLock:lock()的非阻塞、有返回值版本,实际调用tryAcquire的非公平版本

2)unlock方法

既然lock是acquire,不难想到,unlock就是release:

    public void unlock() {
        sync.release(1);
    }
    // in AQS
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

tryRelease由Sync类实现:

        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;
        }

主要操作有:1)恢复计数器;2)边界条件检查;3)解除线程对锁的持有;

与信号量、CDL类似,线程释放锁的时候,还会调用unparkSuccessor从等待队列中找一个后继者持有锁,请参见 JUC学习(一):Semaphore信号量

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值