skywang12345

导航

 

 

本章对ReentrantLock包进行基本介绍,这一章主要对ReentrantLock进行概括性的介绍,内容包括:
ReentrantLock介绍
ReentrantLock函数列表
ReentrantLock示例
在后面的两章,会分别介绍ReentrantLock的两个子类(公平锁和非公平锁)的实现原理。
转载请注明出处:http://www.cnblogs.com/skywang12345/p/3496101.html

 

ReentrantLock介绍

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

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

 

ReentrantLock函数列表

// 创建一个 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”和“示例2”,我们能够清晰的认识lock和unlock的作用

示例1

 1 import java.util.concurrent.locks.Lock;
 2 import java.util.concurrent.locks.ReentrantLock;
 3 
 4 // LockTest1.java
 5 // 仓库
 6 class Depot { 
 7     private int size;        // 仓库的实际数量
 8     private Lock lock;        // 独占锁
 9 
10     public Depot() {
11         this.size = 0;
12         this.lock = new ReentrantLock();
13     }
14 
15     public void produce(int val) {
16         lock.lock();
17         try {
18             size += val;
19             System.out.printf("%s produce(%d) --> size=%d\n", 
20                     Thread.currentThread().getName(), val, size);
21         } finally {
22             lock.unlock();
23         }
24     }
25 
26     public void consume(int val) {
27         lock.lock();
28         try {
29             size -= val;
30             System.out.printf("%s consume(%d) <-- size=%d\n", 
31                     Thread.currentThread().getName(), val, size);
32         } finally {
33             lock.unlock();
34         }
35     }
36 }; 
37 
38 // 生产者
39 class Producer {
40     private Depot depot;
41     
42     public Producer(Depot depot) {
43         this.depot = depot;
44     }
45 
46     // 消费产品:新建一个线程向仓库中生产产品。
47     public void produce(final int val) {
48         new Thread() {
49             public void run() {
50                 depot.produce(val);
51             }
52         }.start();
53     }
54 }
55 
56 // 消费者
57 class Customer {
58     private Depot depot;
59     
60     public Customer(Depot depot) {
61         this.depot = depot;
62     }
63 
64     // 消费产品:新建一个线程从仓库中消费产品。
65     public void consume(final int val) {
66         new Thread() {
67             public void run() {
68                 depot.consume(val);
69             }
70         }.start();
71     }
72 }
73 
74 public class LockTest1 {  
75     public static void main(String[] args) {  
76         Depot mDepot = new Depot();
77         Producer mPro = new Producer(mDepot);
78         Customer mCus = new Customer(mDepot);
79 
80         mPro.produce(60);
81         mPro.produce(120);
82         mCus.consume(90);
83         mCus.consume(150);
84         mPro.produce(110);
85     }
86 }

运行结果

Thread-0 produce(60) --> size=60
Thread-1 produce(120) --> size=180
Thread-3 consume(150) <-- size=30
Thread-2 consume(90) <-- size=-60
Thread-4 produce(110) --> size=50

结果分析
(01) Depot 是个仓库。通过produce()能往仓库中生产货物,通过consume()能消费仓库中的货物。通过独占锁lock实现对仓库的互斥访问:在操作(生产/消费)仓库中货品前,会先通过lock()锁住仓库,操作完之后再通过unlock()解锁。
(02) Producer是生产者类。调用Producer中的produce()函数可以新建一个线程往仓库中生产产品。
(03) Customer是消费者类。调用Customer中的consume()函数可以新建一个线程消费仓库中的产品。
(04) 在主线程main中,我们会新建1个生产者mPro,同时新建1个消费者mCus。它们分别向仓库中生产/消费产品。
根据main中的生产/消费数量,仓库最终剩余的产品应该是50。运行结果是符合我们预期的!

这个模型存在两个问题:
(01) 现实中,仓库的容量不可能为负数。但是,此模型中的仓库容量可以为负数,这与现实相矛盾!
(02) 现实中,仓库的容量是有限制的。但是,此模型中的容量确实没有限制的!
这两个问题,我们稍微会讲到如何解决。现在,先看个简单的示例2;通过对比“示例1”和“示例2”,我们能更清晰的认识lock(),unlock()的用途。

 

示例2

 1 import java.util.concurrent.locks.Lock;
 2 import java.util.concurrent.locks.ReentrantLock;
 3 
 4 // LockTest2.java
 5 // 仓库
 6 class Depot { 
 7     private int size;        // 仓库的实际数量
 8     private Lock lock;        // 独占锁
 9 
10     public Depot() {
11         this.size = 0;
12         this.lock = new ReentrantLock();
13     }
14 
15     public void produce(int val) {
16 //        lock.lock();
17 //        try {
18             size += val;
19             System.out.printf("%s produce(%d) --> size=%d\n", 
20                     Thread.currentThread().getName(), val, size);
21 //        } catch (InterruptedException e) {
22 //        } finally {
23 //            lock.unlock();
24 //        }
25     }
26 
27     public void consume(int val) {
28 //        lock.lock();
29 //        try {
30             size -= val;
31             System.out.printf("%s consume(%d) <-- size=%d\n", 
32                     Thread.currentThread().getName(), val, size);
33 //        } finally {
34 //            lock.unlock();
35 //        }
36     }
37 }; 
38 
39 // 生产者
40 class Producer {
41     private Depot depot;
42     
43     public Producer(Depot depot) {
44         this.depot = depot;
45     }
46 
47     // 消费产品:新建一个线程向仓库中生产产品。
48     public void produce(final int val) {
49         new Thread() {
50             public void run() {
51                 depot.produce(val);
52             }
53         }.start();
54     }
55 }
56 
57 // 消费者
58 class Customer {
59     private Depot depot;
60     
61     public Customer(Depot depot) {
62         this.depot = depot;
63     }
64 
65     // 消费产品:新建一个线程从仓库中消费产品。
66     public void consume(final int val) {
67         new Thread() {
68             public void run() {
69                 depot.consume(val);
70             }
71         }.start();
72     }
73 }
74 
75 public class LockTest2 {  
76     public static void main(String[] args) {  
77         Depot mDepot = new Depot();
78         Producer mPro = new Producer(mDepot);
79         Customer mCus = new Customer(mDepot);
80 
81         mPro.produce(60);
82         mPro.produce(120);
83         mCus.consume(90);
84         mCus.consume(150);
85         mPro.produce(110);
86     }
87 }

(某一次)运行结果

Thread-0 produce(60) --> size=-60
Thread-4 produce(110) --> size=50
Thread-2 consume(90) <-- size=-60
Thread-1 produce(120) --> size=-60
Thread-3 consume(150) <-- size=-60

结果说明
“示例2”在“示例1”的基础上去掉了lock锁。在“示例2”中,仓库中最终剩余的产品是-60,而不是我们期望的50。原因是我们没有实现对仓库的互斥访问。

 

示例3

在“示例3”中,我们通过Condition去解决“示例1”中的两个问题:“仓库的容量不可能为负数”以及“仓库的容量是有限制的”。
解决该问题是通过Condition。Condition是需要和Lock联合使用的:通过Condition中的await()方法,能让线程阻塞[类似于wait()];通过Condition的signal()方法,能让唤醒线程[类似于notify()]。

  1 import java.util.concurrent.locks.Lock;
  2 import java.util.concurrent.locks.ReentrantLock;
  3 import java.util.concurrent.locks.Condition;
  4 
  5 // LockTest3.java
  6 // 仓库
  7 class Depot {
  8     private int capacity;    // 仓库的容量
  9     private int size;        // 仓库的实际数量
 10     private Lock lock;        // 独占锁
 11     private Condition fullCondtion;            // 生产条件
 12     private Condition emptyCondtion;        // 消费条件
 13 
 14     public Depot(int capacity) {
 15         this.capacity = capacity;
 16         this.size = 0;
 17         this.lock = new ReentrantLock();
 18         this.fullCondtion = lock.newCondition();
 19         this.emptyCondtion = lock.newCondition();
 20     }
 21 
 22     public void produce(int val) {
 23         lock.lock();
 24         try {
 25              // left 表示“想要生产的数量”(有可能生产量太多,需多此生产)
 26             int left = val;
 27             while (left > 0) {
 28                 // 库存已满时,等待“消费者”消费产品。
 29                 while (size >= capacity)
 30                     fullCondtion.await();
 31                 // 获取“实际生产的数量”(即库存中新增的数量)
 32                 // 如果“库存”+“想要生产的数量”>“总的容量”,则“实际增量”=“总的容量”-“当前容量”。(此时填满仓库)
 33                 // 否则“实际增量”=“想要生产的数量”
 34                 int inc = (size+left)>capacity ? (capacity-size) : left;
 35                 size += inc;
 36                 left -= inc;
 37                 System.out.printf("%s produce(%3d) --> left=%3d, inc=%3d, size=%3d\n", 
 38                         Thread.currentThread().getName(), val, left, inc, size);
 39                 // 通知“消费者”可以消费了。
 40                 emptyCondtion.signal();
 41             }
 42         } catch (InterruptedException e) {
 43         } finally {
 44             lock.unlock();
 45         }
 46     }
 47 
 48     public void consume(int val) {
 49         lock.lock();
 50         try {
 51             // left 表示“客户要消费数量”(有可能消费量太大,库存不够,需多此消费)
 52             int left = val;
 53             while (left > 0) {
 54                 // 库存为0时,等待“生产者”生产产品。
 55                 while (size <= 0)
 56                     emptyCondtion.await();
 57                 // 获取“实际消费的数量”(即库存中实际减少的数量)
 58                 // 如果“库存”<“客户要消费的数量”,则“实际消费量”=“库存”;
 59                 // 否则,“实际消费量”=“客户要消费的数量”。
 60                 int dec = (size<left) ? size : left;
 61                 size -= dec;
 62                 left -= dec;
 63                 System.out.printf("%s consume(%3d) <-- left=%3d, dec=%3d, size=%3d\n", 
 64                         Thread.currentThread().getName(), val, left, dec, size);
 65                 fullCondtion.signal();
 66             }
 67         } catch (InterruptedException e) {
 68         } finally {
 69             lock.unlock();
 70         }
 71     }
 72 
 73     public String toString() {
 74         return "capacity:"+capacity+", actual size:"+size;
 75     }
 76 }; 
 77 
 78 // 生产者
 79 class Producer {
 80     private Depot depot;
 81     
 82     public Producer(Depot depot) {
 83         this.depot = depot;
 84     }
 85 
 86     // 消费产品:新建一个线程向仓库中生产产品。
 87     public void produce(final int val) {
 88         new Thread() {
 89             public void run() {
 90                 depot.produce(val);
 91             }
 92         }.start();
 93     }
 94 }
 95 
 96 // 消费者
 97 class Customer {
 98     private Depot depot;
 99     
100     public Customer(Depot depot) {
101         this.depot = depot;
102     }
103 
104     // 消费产品:新建一个线程从仓库中消费产品。
105     public void consume(final int val) {
106         new Thread() {
107             public void run() {
108                 depot.consume(val);
109             }
110         }.start();
111     }
112 }
113 
114 public class LockTest3 {  
115     public static void main(String[] args) {  
116         Depot mDepot = new Depot(100);
117         Producer mPro = new Producer(mDepot);
118         Customer mCus = new Customer(mDepot);
119 
120         mPro.produce(60);
121         mPro.produce(120);
122         mCus.consume(90);
123         mCus.consume(150);
124         mPro.produce(110);
125     }
126 }

(某一次)运行结果

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

代码中的已经包含了很详细的注释,这里就不再说明了。
更多“生产者/消费者模型”的更多内容,可以参考“Java多线程系列--“基础篇”11之 生产消费者问题”。
而关于Condition的内容,在后面我们会详细介绍。

 


更多内容

1. Java多线程系列--“JUC锁”01之 框架

2. Java多线程系列目录(共xx篇)

 

posted on 2014-01-19 21:54  如果天空不死  阅读(29384)  评论(14编辑  收藏  举报