java中ReentrantLock的作用是什么

发布时间:2021-06-11 15:38:15 作者:Leah
来源:亿速云 阅读:148

今天就跟大家聊聊有关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)

看完上述内容,你们对java中ReentrantLock的作用是什么有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. java中ReentrantLock类如何使用
  2. ReentrantLock的实现原理是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java reentrantlock

上一篇:PHP设计模式之工厂模式怎么用

下一篇:PHP命名空间namespace定义及导入use的使用示例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》