当前位置: 移动技术网 > IT编程>开发语言>Java > Java concurrency之互斥锁_动力节点Java学院整理

Java concurrency之互斥锁_动力节点Java学院整理

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

 import java.util.concurrent.locks.lock;
 import java.util.concurrent.locks.reentrantlock;
 // locktest.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 locktest1 { 
   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);
   }
 }

运行结果:

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

 import java.util.concurrent.locks.lock;
 import java.util.concurrent.locks.reentrantlock;
 // locktest.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);
 //    } catch (interruptedexception e) {
 //    } 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 locktest2 { 
   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);
   }
 }

(某一次)运行结果:

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()]。

 import java.util.concurrent.locks.lock;
  import java.util.concurrent.locks.reentrantlock;
  import java.util.concurrent.locks.condition;
  // locktest.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 = ;
     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 > ) {
         // 库存已满时,等待“消费者”消费产品。
         while (size >= capacity)
           fullcondtion.await();
         // 获取“实际生产的数量”(即库存中新增的数量)
         // 如果“库存”+“想要生产的数量”>“总的容量”,则“实际增量”=“总的容量”-“当前容量”。(此时填满仓库)
         // 否则“实际增量”=“想要生产的数量”
         int inc = (size+left)>capacity ? (capacity-size) : left;
         size += inc;
         left -= inc;
         system.out.printf("%s produce(%d) --> left=%d, inc=%d, size=%d\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 > ) {
         // 库存为时,等待“生产者”生产产品。
         while (size <= )
           emptycondtion.await();
         // 获取“实际消费的数量”(即库存中实际减少的数量)
         // 如果“库存”<“客户要消费的数量”,则“实际消费量”=“库存”;
         // 否则,“实际消费量”=“客户要消费的数量”。
         int dec = (size<left) ? size : left;
         size -= dec;
         left -= dec;
         system.out.printf("%s consume(%d) <-- left=%d, dec=%d, size=%d\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 locktest3 { 
   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);
   }
 }

(某一次)运行结果:

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 concurrency之互斥锁,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网