首页 > 代码库 > 多线程编程-- part5.1 互斥锁ReentrantLock

多线程编程-- part5.1 互斥锁ReentrantLock

ReentrantLock简介

  Reentrantlock是一个可重入的互斥锁,又被称为独占锁。

  Reentrantlock:分为公平锁和非公平锁,它们的区别体现在获取锁的机制上是否公平。“锁”是为了保护竞争资源,防止多个线程同时操作线程而出错,ReentrantLock在同一个时间点只能被一个线程获取(当某线程获取到“锁”时,其它线程就必须等待);ReentraantLock是通过一个FIFO的等待队列来管理获取该锁所有线程的。在“公平锁”的机制下,线程依次排队获取锁;而“非公平锁”在锁是可获取状态时,不管自己是不是在队列的开头都会获取锁。

// 创建一个 ReentrantLock ,默认是“非公平锁”。ReentrantLock()// 创建策略是fair的 ReentrantLock。fair为true表示是公平锁,fair为false表示是非公平锁。ReentrantLock(boolean fair)// 查询当前线程保持此锁的次数。int getHoldCount()// 返回目前拥有此锁的线程,如果此锁不被任何线程拥有,则返回 null。protected Thread getOwner()// 返回一个 collection,它包含可能正等待获取此锁的线程。protected Collection<Thread> getQueuedThreads()// 返回正等待获取此锁的线程估计数。int getQueueLength()// 返回一个 collection,它包含可能正在等待与此锁相关给定条件的那些线程。protected Collection<Thread> getWaitingThreads(Condition condition)// 返回等待与此锁相关的给定条件的线程估计数。int getWaitQueueLength(Condition condition)// 查询给定线程是否正在等待获取此锁。boolean hasQueuedThread(Thread thread)// 查询是否有些线程正在等待获取此锁。boolean hasQueuedThreads()// 查询是否有些线程正在等待与此锁有关的给定条件。boolean hasWaiters(Condition condition)// 如果是“公平锁”返回true,否则返回false。boolean isFair()// 查询当前线程是否保持此锁。boolean isHeldByCurrentThread()// 查询此锁是否由任意线程保持。boolean isLocked()// 获取锁。void lock()// 如果当前线程未被中断,则获取锁。void lockInterruptibly()// 返回用来与此 Lock 实例一起使用的 Condition 实例。Condition newCondition()// 仅在调用时锁未被另一个线程保持的情况下,才获取该锁。boolean tryLock()// 如果锁在给定等待时间内没有被另一个线程保持,且当前线程未被中断,则获取该锁。boolean tryLock(long timeout, TimeUnit unit)// 试图释放此锁。void unlock()

 

ReentrantLock示例:生产者消费者

测试1:用独占锁控制生产和消费,确保不会同时发生

package com.template.ProduceConsume;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;// LockTest1.java// 仓库class Depot {    private int size;        // 仓库的实际数量    private Lock lock;        // 独占锁    public Depot() {        this.size = 0;        this.lock = new ReentrantLock();    }    public void produce(int val) {        lock.lock();        try {            size += val;            System.out.printf("%s produce(%d) --> size=%d\n",                    Thread.currentThread().getName(), val, size);        } finally {            lock.unlock();        }    }    public void consume(int val) {        lock.lock();        try {            size -= val;            System.out.printf("%s consume(%d) <-- size=%d\n",                    Thread.currentThread().getName(), val, size);        } finally {            lock.unlock();        }    }};// 生产者class Producer {    private Depot depot;    public Producer(Depot depot) {        this.depot = depot;    }    // 消费产品:新建一个线程向仓库中生产产品。    public void produce(final int val) {        new Thread() {            public void run() {                depot.produce(val);            }        }.start();    }}// 消费者class Customer {    private Depot depot;    public Customer(Depot depot) {        this.depot = depot;    }    // 消费产品:新建一个线程从仓库中消费产品。    public void consume(final int val) {        new Thread() {            public void run() {                depot.consume(val);            }        }.start();    }}public class test {    public static void main(String[] args) {        Depot mDepot = new Depot();        Producer mPro = new Producer(mDepot);        Customer mCus = new Customer(mDepot);        mPro.produce(60);        mPro.produce(120);        mCus.consume(90);        mCus.consume(150);        mPro.produce(110);    }}

技术分享

 

2.去掉锁之后

技术分享

 

3.用condition保证仓库库存不为负数,仓库容量有限制

package com.template.ProduceConsume;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;import java.util.concurrent.locks.Condition;// LockTest3.java// 仓库class Depot {    private int capacity;    // 仓库的容量    private int size;        // 仓库的实际数量    private Lock lock;        // 独占锁    private Condition fullCondtion;            // 生产条件    private Condition emptyCondtion;        // 消费条件    public Depot(int capacity) {        this.capacity = capacity;        this.size = 0;        this.lock = new ReentrantLock();        this.fullCondtion = lock.newCondition();        this.emptyCondtion = lock.newCondition();    }    public void produce(int val) {        lock.lock();        try {            // left 表示“想要生产的数量”(有可能生产量太多,需多此生产)            int left = val;            while (left > 0) {                // 库存已满时,等待“消费者”消费产品。                while (size >= capacity)                    fullCondtion.await();                System.out.println("生产开始了");                // 获取“实际生产的数量”(即库存中新增的数量)                // 如果“库存”+“想要生产的数量”>“总的容量”,则“实际增量”=“总的容量”-“当前容量”。(此时填满仓库)                // 否则“实际增量”=“想要生产的数量”                int inc = (size+left)>capacity ? (capacity-size) : left;                size += inc;                left -= inc;                System.out.printf("%s produce(%3d) --> left=%3d, inc=%3d, size=%3d\n",                        Thread.currentThread().getName(), val, left, inc, size);                // 通知“消费者”可以消费了。                emptyCondtion.signal();            }        } catch (InterruptedException e) {        } finally {            lock.unlock();        }    }    public void consume(int val) {        lock.lock();        try {            // left 表示“客户要消费数量”(有可能消费量太大,库存不够,需多此消费)            int left = val;            while (left > 0) {                // 库存为0时,等待“生产者”生产产品。                while (size <= 0)                    emptyCondtion.await();                System.out.println("消费开始");                // 获取“实际消费的数量”(即库存中实际减少的数量)                // 如果“库存”<“客户要消费的数量”,则“实际消费量”=“库存”;                // 否则,“实际消费量”=“客户要消费的数量”。                int dec = (size<left) ? size : left;                size -= dec;                left -= dec;                System.out.printf("%s consume(%3d) <-- left=%3d, dec=%3d, size=%3d\n",                        Thread.currentThread().getName(), val, left, dec, size);                fullCondtion.signal();            }        } catch (InterruptedException e) {        } finally {            lock.unlock();        }    }    public String toString() {        return "capacity:"+capacity+", actual size:"+size;    }};// 生产者class Producer {    private Depot depot;    public Producer(Depot depot) {        this.depot = depot;    }    // 消费产品:新建一个线程向仓库中生产产品。    public void produce(final int val) {        new Thread() {            public void run() {                depot.produce(val);            }        }.start();    }}// 消费者class Customer {    private Depot depot;    public Customer(Depot depot) {        this.depot = depot;    }    // 消费产品:新建一个线程从仓库中消费产品。    public void consume(final int val) {        new Thread() {            public void run() {                depot.consume(val);            }        }.start();    }}public class test {    public static void main(String[] args) {        Depot mDepot = new Depot(100);        Producer mPro = new Producer(mDepot);        Customer mCus = new Customer(mDepot);        mPro.produce(60);        mPro.produce(120);        mCus.consume(90);        mCus.consume(150);        mPro.produce(110);    }}

技术分享

 

       引入了两个Condition条件,一个条件是是满了停止生产,等待通知进行生产,一个是空了停止消费,有了通知消费。

多线程编程-- part5.1 互斥锁ReentrantLock