java ReentrantLock详解

 更新时间:2019年04月03日 14:29:11   作者:jihite  
这篇文章主要介绍了java ReentrantLock,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

介绍

ReentrantLock称为重入锁,比内部锁synchonized拥有更强大的功能,它可中断、可定时、设置公平锁

【注】使用ReentrantLock时,一定要释放锁,一般释放放到finnal里写。

提供以下重要的方法

  1. lock():获得锁,如果锁已被占用,则等待
  2. lockInterruptibly():获得锁,但有限响应中断
  3. unlock():释放锁
  4. tryLock():尝试获取锁。如果获得,返回true;否则返回false
  5. tryLock(long time, TimeUnit unit):在给定时间内获得锁。如果获得返回true;否则返回false

示例

例子1

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
 ReentrantLock lock;

 ReentrantLockTest(ReentrantLock lock) {
  this.lock = lock;
 }

 private Runnable getRunnable() {
  return new Runnable() {
   @Override
   public void run() {
    while(true) {
     try {
      if (lock.tryLock()) {
       try {
        System.out.println("Locked:" + Thread.currentThread().getName());
        Thread.sleep(800);
       } finally {
        lock.unlock();
        System.out.println("UnLocked:" + Thread.currentThread().getName());
       }
       System.out.println("break before");
       break;
      } else {
       //System.out.println("Unable to lock " + Thread.currentThread().getName());
      }

     } catch (InterruptedException e){
      System.out.println(Thread.currentThread() + " is Interupted");
      e.printStackTrace();
     }
    }
   }
  };
 }

 public static void main(String[] args) {
  ReentrantLock lock = new ReentrantLock();
  ReentrantLockTest test = new ReentrantLockTest(lock);
  ReentrantLockTest test2 = new ReentrantLockTest(lock);
  Thread thread1 = new Thread(test.getRunnable(), "firstThread");
  Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

  thread1.start();
  thread2.start();
  try {
   Thread.sleep(300);
  }catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("interupt begin");
  thread2.interrupt();
  System.out.println("interupt end");
 }
}

一次执行结果:

Locked:firstThread
interupt begin
interupt end
UnLocked:firstThread
break before
Locked:secondThread
UnLocked:secondThread
Thread[secondThread,5,main] is Interupted
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.jihite.templet.JavaBase.ReentrantLockTest$1.run(ReentrantLockTest.java:23)
    at java.lang.Thread.run(Thread.java:748)
Locked:secondThread
UnLocked:secondThread
break before

 分析:firstThread执行,secondThread不停的判断是否可以获得锁,当firstThread执行完,secondThread执行后被打断

例子2

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
 ReentrantLock lock;

 ReentrantLockTest(ReentrantLock lock) {
  this.lock = lock;
 }

 private Runnable getRunnable() {
  return new Runnable() {
   @Override
   public void run() {
    while(true) {
     try {
      if (lock.tryLock(700, TimeUnit.MILLISECONDS)) {
       try {
        System.out.println("Locked:" + Thread.currentThread().getName());
        Thread.sleep(800);
       } finally {
        lock.unlock();
        System.out.println("UnLocked:" + Thread.currentThread().getName());
       }
       System.out.println("break before");
       break;
      } else {
       //System.out.println("Unable to lock " + Thread.currentThread().getName());
      }

     } catch (InterruptedException e){
      System.out.println(Thread.currentThread() + " is Interupted");
      e.printStackTrace();
     }
    }
   }
  };
 }

 public static void main(String[] args) {
  ReentrantLock lock = new ReentrantLock();
  ReentrantLockTest test = new ReentrantLockTest(lock);
  ReentrantLockTest test2 = new ReentrantLockTest(lock);
  Thread thread1 = new Thread(test.getRunnable(), "firstThread");
  Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

  thread1.start();
  thread2.start();
  try {
   Thread.sleep(300);
  }catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("interupt begin");
  thread2.interrupt();
  System.out.println("interupt end");
 }
}

一次执行结果

Locked:firstThread
interupt begin
interupt end
Thread[secondThread,5,main] is Interupted
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireNanos(AbstractQueuedSynchronizer.java:936)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireNanos(AbstractQueuedSynchronizer.java:1247)
    at java.util.concurrent.locks.ReentrantLock.tryLock(ReentrantLock.java:442)
    at com.jihite.templet.JavaBase.ReentrantLockTest$1.run(ReentrantLockTest.java:19)
    at java.lang.Thread.run(Thread.java:748)
Locked:secondThread
UnLocked:firstThread
break before
UnLocked:secondThread
break before

分析:firstThread执行,secondThread等待,等待过程被打断。打断后firstThread执行结束了,secondThread得到锁,继续执行

例子3

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest2 {
 ReentrantLock lock;

 ReentrantLockTest2(ReentrantLock lock) {
  this.lock = lock;
 }

 private Runnable getRunnable() {
  return new Runnable() {
   @Override
   public void run() {
    while (true) {
     try {
      try {
       lock.lock();
//       lock.lockInterruptibly();
       System.out.println("Locked:" + Thread.currentThread().getName());
       Thread.sleep(800);
       break;
      } finally {
       lock.unlock();
       System.out.println("UnLocked:" + Thread.currentThread().getName());
      }
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
  };
 }

 public static void main(String[] args) {
  ReentrantLock lock = new ReentrantLock();
  ReentrantLockTest2 test = new ReentrantLockTest2(lock);
  ReentrantLockTest2 test2 = new ReentrantLockTest2(lock);
  Thread thread1 = new Thread(test.getRunnable(), "firstThread");
  Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

  thread1.start();
  thread2.start();
  try {
   Thread.sleep(600);
  }catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("interupt begin");
  thread2.interrupt();
  System.out.println("interupt end");
 }
}

一次执行结果

Locked:firstThread
interupt begin
interupt end
UnLocked:firstThread
Locked:secondThread
UnLocked:secondThread
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.jihite.templet.JavaBase.ReentrantLockTest2$1.run(ReentrantLockTest2.java:22)
    at java.lang.Thread.run(Thread.java:748)
Locked:secondThread
UnLocked:secondThread

分析:firstThread先获得锁执行,secondThread在等待,此时中断并未打断等待。firstThread执行完,secondThread获取后被打断

例子4

public class ReentrantLockTest2 {
 ReentrantLock lock;

 ReentrantLockTest2(ReentrantLock lock) {
  this.lock = lock;
 }

 private Runnable getRunnable() {
  return new Runnable() {
   @Override
   public void run() {
    while (true) {
     try {
      try {
//       lock.lock();
       lock.lockInterruptibly();
       System.out.println("Locked:" + Thread.currentThread().getName());
       Thread.sleep(800);
       break;
      } finally {
       lock.unlock();
       System.out.println("UnLocked:" + Thread.currentThread().getName());
      }
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
  };
 }

 public static void main(String[] args) {
  ReentrantLock lock = new ReentrantLock();
  ReentrantLockTest2 test = new ReentrantLockTest2(lock);
  ReentrantLockTest2 test2 = new ReentrantLockTest2(lock);
  Thread thread1 = new Thread(test.getRunnable(), "firstThread");
  Thread thread2 = new Thread(test2.getRunnable(), "secondThread");

  thread1.start();
  thread2.start();
  try {
   Thread.sleep(600);
  }catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("interupt begin");
  thread2.interrupt();
  System.out.println("interupt end");
 }
}

一次执行结果

Locked:firstThread
interupt begin
interupt end
Exception in thread "secondThread" java.lang.IllegalMonitorStateException
    at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
    at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
    at com.jihite.templet.JavaBase.ReentrantLockTest2$1.run(ReentrantLockTest2.java:25)
    at java.lang.Thread.run(Thread.java:748)

分析:lock.lockInterruptibly();在执行过程中可以响应中断时间

以上所述是小编给大家介绍的java ReentrantLock详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • 详解Java Unsafe如何花式操作内存

    详解Java Unsafe如何花式操作内存

    C++可以动态的分类内存,而java并不能这样,是不是java就不能操作内存呢,其实是有其他办法可以操作内存的,下面就一起看看Unsafe是如何花式操作内存的吧
    2023-08-08
  • Java日志组件间关系详解

    Java日志组件间关系详解

    在本文里我们给大家整理了关于Java日志组件间关系相关基础知识,需要的朋友们跟着学习下。
    2019-02-02
  • Java 基础之内部类详解及实例

    Java 基础之内部类详解及实例

    这篇文章主要介绍了 Java 基础之内部类详解及实例的相关资料,需要的朋友可以参考下
    2017-03-03
  • 如何自动生成Mybatis的Mapper文件详解

    如何自动生成Mybatis的Mapper文件详解

    这篇文章主要给大家介绍了关于如何自动生成Mybatis的Mapper文件的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Mybatis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-07-07
  • SpringBoot2 整合Nacos组件及环境搭建和入门案例解析

    SpringBoot2 整合Nacos组件及环境搭建和入门案例解析

    这篇文章主要介绍了SpringBoot2 整合Nacos组件,环境搭建和入门案例详解,在整合springboot2时注意版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本,具体内容详情跟随小编一起看看吧
    2022-03-03
  • 使用Java方法配置Spring代码解析

    使用Java方法配置Spring代码解析

    这篇文章主要介绍了使用Java方法配置Spring代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • Java split函数拆分后变成null问题解决方案

    Java split函数拆分后变成null问题解决方案

    这篇文章主要介绍了Java split函数拆分后变成null问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • 基于FlashPaper实现JSP在线阅读代码示例

    基于FlashPaper实现JSP在线阅读代码示例

    这篇文章主要介绍了基于FlashPaper实现JSP在线阅读代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • java 数据结构与算法 (快速排序法)

    java 数据结构与算法 (快速排序法)

    这篇文章主要介绍了java 数据结构与算法(快速排序法),,快速排序法是实践中的一种快速的排序算法,在c++或对java基本类型的排序中特别有用,下面我们一起进入文章学习更详细的内容吧,需要的朋友可以参考下
    2022-02-02
  • SpringBoot实现动态数据源切换的方法总结

    SpringBoot实现动态数据源切换的方法总结

    项目开发中经常会遇到多数据源同时使用的场景,比如冷热数据的查询等情况,所以接下来本文就来介绍一下如何使用实现自定义注解的形式来实现动态数据源切换吧
    2023-12-12

最新评论