Java多線程系列--「JUC鎖」02之 互斥鎖ReentrantLock

 

本章對ReentrantLock包進行基本介紹,這一章主要對ReentrantLock進行歸納性的介紹,內容包括:
ReentrantLock介紹
ReentrantLock函數列表
ReentrantLock示例
在後面的兩章,會分別介紹ReentrantLock的兩個子類(公平鎖和非公平鎖)的實現原理。
轉載請註明出處:http://www.cnblogs.com/skywang12345/p/3496101.htmlhtml

 

ReentrantLock介紹

ReentrantLock是一個可重入的互斥鎖,又被稱爲「獨佔鎖」。java

顧名思義,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 }

運行結果this

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。運行結果是符合咱們預期的!spa

這個模型存在兩個問題:
(01) 現實中,倉庫的容量不可能爲負數。可是,此模型中的倉庫容量能夠爲負數,這與現實相矛盾!
(02) 現實中,倉庫的容量是有限制的。可是,此模型中的容量確實沒有限制的!
這兩個問題,咱們稍微會講到如何解決。如今,先看個簡單的示例2;經過對比「示例1」和「示例2」,咱們能更清晰的認識lock(),unlock()的用途。線程

 

示例23d

 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 }

(某一次)運行結果code

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篇)

相關文章
相關標籤/搜索