当前位置: 首页 > 编程笔记 >

java ReentrantLock详解

包嘉懿
2023-03-14
本文向大家介绍java ReentrantLock详解,包括了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详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对小牛知识库网站的支持!

 类似资料:
  • 本文向大家介绍awk 详解。相关面试题,主要包含被问及awk 详解。时的应答技巧和注意事项,需要的朋友参考一下 答案: awk '{pattern + action}' { filenames } #cat /etc/passwd |awk -F ':' '{print 1"t"7}' //-F 的意思是以':'分隔 root /bin/bash daemon /bin/sh 搜索/etc/pas

  • glob 是由普通字符和/或通配字符组成的字符串,用于匹配文件路径。可以利用一个或多个 glob 在文件系统中定位文件。 src() 方法接受一个 glob 字符串或由多个 glob 字符串组成的数组作为参数,用于确定哪些文件需要被操作。glob 或 glob 数组必须至少匹配到一个匹配项,否则 src() 将报错。当使用 glob 数组时,将按照每个 glob 在数组中的位置依次执行匹配 - 这

  • scanf()函数详解 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> //01.scanf();函数扫描输入事项: // 格式必须一一匹配:非格式控制符的可见字符必须一一匹配输入 int main01(void) { int num = 0; printf("%p \n", &nu

  • printf()详解 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> //01.printf();&sprintf();&fprintf();格式控制字符串详解: // (1).格式控制字符串的组成: // 普通字符串+格式控制符 // (2).常见的格式控制字符: // %f-

  • 主要内容:state状态,自定义资源共享方式,源码实现AQS是AbstractQueuedSynchronizer的简称。AQS提供了一种实现阻塞锁和一系列依赖FIFO等待队列的同步器的框架,如下图所示。AQS为一系列同步器依赖于一个单独的原子变量(state)的同步器提供了一个非常有用的基础。子类们必须定义改变state变量的protected方法,这些方法定义了state是如何被获取或释放的。鉴于此,本类中的其他方法执行所有的排队和阻塞机制。子类

  • 主要内容:state状态,自定义资源共享方式,源码实现AQS是AbstractQueuedSynchronizer的简称。AQS提供了一种实现阻塞锁和一系列依赖FIFO等待队列的同步器的框架,如下图所示。AQS为一系列同步器依赖于一个单独的原子变量(state)的同步器提供了一个非常有用的基础。子类们必须定义改变state变量的protected方法,这些方法定义了state是如何被获取或释放的。鉴于此,本类中的其他方法执行所有的排队和阻塞机制。子类

  • 主要内容:6 DataNode(面试开发重点)6 DataNode(面试开发重点) 6.1 DataNode工作机制 DataNode工作机制,如图3-15所示。 1)一个数据块在DataNode上以文件形式存储在磁盘上,包括两个文件,一个是数据本身,一个是元数据包括数据块的长度,块数据的校验和,以及时间戳。 2)DataNode启动后向NameNode注册,通过后,周期性(1小时)的向NameNode上报所有的块信息。 3)心跳是每3秒一次

  • 主要内容:4 HDFS的数据流,5 NameNode和SecondaryNameNode(面试开发重点)4 HDFS的数据流 4.1 HDFS写数据流程 4.1.1 剖析文件写入 HDFS写数据流程 1)客户端通过Distributed FileSystem模块向NameNode请求上传文件,NameNode检查目标文件是否已存在,父目录是否存在。 2)NameNode返回是否可以上传。 3)客户端请求第一个 Block上传到哪几个DataNode服务器上。 4)NameNode返回3个Data