Java之JUC系列(03)--互斥锁ReentrantLock

来源:互联网 发布:tabe知乎 编辑:程序博客网 时间:2024/06/05 00:33

一、ReentrantLock基本介绍

ReentrantLock是一个可重入的互斥锁,又被称为“互斥锁”。
ReentrantLock锁(互斥锁):指在同一个时间点只能被一个线程所持有;可重入则是说ReentrantLock可以被单个线程多次获取。
ReentrantLock分为“公平锁”和“非公平锁”。它们主要是体现在多个线程获取该锁的机制上是否公平。“锁”是为了保护竞争资源,防止多个线程同时操作线程而出错,ReentrantLock在同一个时间点只能被一个线程获取;ReentrantLock是通过一个FIFO的等待队列来管理获取该锁的所有线程。在公平锁的机制下,线程依次排队获取该锁;而非公平锁机制下,不管自己是不是在队列的开头都会获取该锁。

二、ReentrantLock常用API

//创建一个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(Conditon condition)//返回等待与此锁相关条件的线程估计数int getWaitQueueLength(Condition condition)//查询给定线程是否正在等待获取此锁boolean hasQueuedThread(Thread thread)//查询是否有线程正在等待获取此锁boolean hasQueuedThreads()//查询是否有些线程正在等待与此锁有关的给定条件boolean hasWaiters(Condition condition)//如果是公平锁,返回true,否则返回falseboolean isFair()//查询当前线程是否保持此锁boolean isHeldByCurrentThread()//查询此锁是否由任意线程保持boolean isLocked()//获取锁void lock()//如果当前线程未被中断,则获取锁void lockInterruptibly()//返回用来与此lock实例一起使用的Condition实例Condition newCondition()//仅在调用时锁未被另一个线程保持,且当前线程未被中断,则获取该锁boolean tryLock(long timeout,TimeUnit unit)//试图释放此锁void unlock()

三、ReentrantLock代码实例

(1)代码如下:

package MultiConsumerAndProduct;/** * Created by LKL on 2017/2/23. */public class TestLock {    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(200);        mPro.produce(110);    }}
package MultiConsumerAndProduct;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * Created by LKL on 2017/2/23. */public class Depot {    private int size;    private Lock lock;    public Depot(){        this.size=0;    //仓库的数量刚开始为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 produce(%d) --> size=%d\n", Thread.currentThread().getName(), val, size);        } finally {            lock.unlock();        }    }}
package MultiConsumerAndProduct;/** * Created by LKL on 2017/2/23. */public 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();    }}
package MultiConsumerAndProduct;/** * Created by LKL on 2017/2/23. */public 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();    }}

运行结果如下:

Thread-0 produce(60) --> size=60Thread-1 produce(120) --> size=180Thread-2 produce(90) --> size=90Thread-3 produce(200) --> size=-110Thread-4 produce(110) --> size=0

上述结果分析:
1>Depot是个仓库,通过produce()能往仓库中生产货物,通过consume()能消费仓库中的货物,通过独占锁lock实现对仓库的互斥访问:在操作(生产/消费)仓库中的货品前,会先通过lock()锁住仓库,操作完之后再通过unlock()解锁。
2>Producer是生产者类,调用Producer中的produce()函数可以新建一个线程往仓库中生产产品。
3>Customer是消费者类,调用Customer中的consume()可以新建一个线程消费仓库中的产品。
4>在主线程main中,我们会新建一个生产者mPro,同时新建一个消费者mCus,他们分别向仓库中生产或者消费产品。
细心的可以观察到,仓库中的数量出现负数,这在现实中是不允许出现的情况,后面继续解决。
(2)下面通过Condition去解决上述存在的问题。Condition需要和Lock配合使用:通过Condition中的await()方法,能让线程阻塞(类似于wait());通过Condition的signal()方法,能唤醒线程(类似于notify());
代码如下:

package MultiConsumerAndProduct1;import MultiConsumerAndProduct.Customer;import MultiConsumerAndProduct.Producer;/** * Created by LKL on 2017/2/23. */public class TestLock1 {    public static void main(String[] args){        //仓库中总量设置为100        Depot1 mDepot1 = new Depot1(100);        Producer1 mPro = new Producer1(mDepot1);        Customer1 mCus = new Customer1(mDepot1);        mPro.produce1(60);        mPro.produce1(120);        mCus.consume1(90);        mCus.consume1(150);        mPro.produce1(110);    }}
package MultiConsumerAndProduct1;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * Created by LKL on 2017/2/23. */public class Depot1 {    private int capacity;    // 仓库的容量    private int size;        // 仓库的实际数量    private Lock lock;        // 独占锁    private Condition fullCondtion;            // 生产条件    private Condition emptyCondtion;        // 消费条件    public Depot1(int capacity) {        this.capacity = capacity;        this.size = 0;        this.lock = new ReentrantLock();        this.fullCondtion = lock.newCondition();        this.emptyCondtion = lock.newCondition();    }    public void produce1(int val) {        lock.lock();        try {            // left 表示“想要生产的数量”(有可能生产量太多,需多此生产)            int left = val;            while (left > 0) {                // 库存已满时,等待“消费者”消费产品。                while (size >= capacity)                    fullCondtion.await();                // 获取“实际生产的数量”(即库存中新增的数量)                // 如果“库存”+“想要生产的数量”>“总的容量”,则“实际增量”=“总的容量”-“当前容量”。(此时填满仓库)                // 否则“实际增量”=“想要生产的数量”                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.signalAll();            }        } catch (InterruptedException e) {        } finally {            lock.unlock();        }    }    public void consume1(int val) {        lock.lock();        try {            // left 表示“客户要消费数量”(有可能消费量太大,库存不够,需多此消费)            int left = val;            while (left > 0) {                // 库存为0时,等待“生产者”生产产品。                while (size <= 0)                    emptyCondtion.await();                // 获取“实际消费的数量”(即库存中实际减少的数量)                // 如果“库存”<“客户要消费的数量”,则“实际消费量”=“库存”;                // 否则,“实际消费量”=“客户要消费的数量”。                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.signalAll();            }        } catch (InterruptedException e) {        } finally {            lock.unlock();        }    }    public String toString() {        return "capacity:"+capacity+", actual size:"+size;    }}
package MultiConsumerAndProduct1;/** * Created by LKL on 2017/2/23. */public class Producer1 {    private Depot1 depot;    public Producer1(Depot1 depot) {        this.depot = depot;    }    //消费产品:新建一个线程向仓库中生产商品    public void produce1(final int val){        new Thread(){            public void run() {                depot.produce1(val);            }        }.start();    }}
package MultiConsumerAndProduct1;/** * Created by LKL on 2017/2/23. */public class Customer1 {    private Depot1 depot;    public Customer1(Depot1 depot) {        this.depot = depot;    }    //消费产品:新建一个线程从仓库中消费产品    public void consume1(final int val){        new Thread(){            public void run(){                depot.consume1(val);            }        }.start();    }}

运行结果如下:

Thread-0 produce( 60) --> left=  0, inc= 60, size= 60Thread-1 produce(120) --> left= 80, inc= 40, size=100Thread-2 consume( 90) <-- left=  0, dec= 90, size= 10Thread-3 consume(150) <-- left=140, dec= 10, size=  0Thread-4 produce(110) --> left= 10, inc=100, size=100Thread-3 consume(150) <-- left= 40, dec=100, size=  0Thread-4 produce(110) --> left=  0, inc= 10, size= 10Thread-3 consume(150) <-- left= 30, dec= 10, size=  0Thread-1 produce(120) --> left=  0, inc= 80, size= 80Thread-3 consume(150) <-- left=  0, dec= 30, size= 50

结果分析:
1>上述结果中left表示生产或消费多余的数量,inc/dec为仓库中增加或减少的数量,size为仓库中产品的数量。首先得明白在主线程main中设置了仓库中总量为100。
2>Producer1是生产者类,调用Producer1中的produce1()函数可以新建一个线程往仓库中生产产品。
3>Customer1是消费者类,调用Customer1中的consume1()可以新建一个线程消费仓库中的产品。
4>在主线程main中,我们会新建一个生产者mPro,同时新建一个消费者mCus,他们分别向仓库中生产或者消费产品。

文章只是作为自己的学习笔记,借鉴了网上的许多案例,如果觉得阔以的话,希望多交流,在此谢过…

0 0
原创粉丝点击