1、可重入锁是可以中断的,如果发生了死锁,可以中断程序

 //如下程序出现死锁,不去kill jvm无法解决死锁
public class Uninterruptible {
public static void main(String[] args) throws InterruptedException {
final Object o1 = new Object(); final Object o2 = new Object();
Thread t1 = new Thread() {
public void run() {
try {
synchronized(o1) {
Thread.sleep(1000);
synchronized(o2) {}
}
} catch (InterruptedException e) { System.out.println("t1 interrupted"); }
}
};
Thread t2 = new Thread() {
public void run() {
try {
synchronized(o2) {
Thread.sleep(1000);
synchronized(o1) {}
}
} catch (InterruptedException e) { System.out.println("t2 interrupted"); }
}
};
t1.start();
t2.start();
Thread.sleep(2000);
t1.interrupt();
t2.interrupt();
t1.join();
t2.join();
}
}

然后是解决方法:We can reimplement our threads using Reentrant-Lock instead of intrinsic locks, and we can use its lockInterruptibly() method

Thread A先取得lock,Thread B无法取得lock进入block状态,可以透过发出interrupt方式唤醒Thread B,这就是和lock的区别

  • lock():若lock被thread A取得,thread B会进入block状态,直到取得lock。
  • tryLock():若当下不能取得lock,thread就会放弃。
  • lockInterruptibly():跟lock()情況一下,但是thread B可以透过interrupt被唤醒处理InterruptedException。
 final ReentrantLock l1 = new ReentrantLock();
final ReentrantLock l2 = new ReentrantLock();
Thread t1 = new Thread() {
public void run() {
try {
➤ l1.lockInterruptibly();
Thread.sleep(1000);
➤ l2.lockInterruptibly();
} catch (InterruptedException e) { System.out.println("t1 interrupted"); }
}
};
Thread t2 = new Thread() {
public void run() {
try {
➤ l2.lockInterruptibly();
Thread.sleep(1000);
➤ l1.lockInterruptibly();
} catch (InterruptedException e) { System.out.println("t2 interrupted"); }
}
}; t1.start();
t2.start();
Thread.sleep(2000);
t1.interrupt(); //当执行到时,线程会捕获InterruptedException程序会结束
t2.interrupt();
t1.join();
t2.join();
}

2、设置锁超时时间

  • tryLock():若线程一定时间不能取得lock,thread就会放弃。
 public class LockTimeOut{
private ReentrantLock leftChopstick, rightChopstick;
public void method(){
Thread.sleep(random.nextInt(1000)); // Think for a while
leftChopstick.lock();
try {
➤ if (rightChopstick.tryLock(1000, TimeUnit.MILLISECONDS)) {
// Got the right chopstick
………
} }

  

说明:Instead of using lock(), this code uses tryLock(), which times out if it fails to acquire the lock

3、条件变量,所谓的  Condition: await()/signal(),可以实现每个关注自己的信号量,每个人有每个人的信号量

When you use Condition: await()/signal() you can distinguish which object or group of objects/threads get a specific signal.

Here is a short example where some threads, the producers, will get the isEmpty signal while the consumers will get the isFull signal:

这里会有两个信号量,生产者和消费这关注的信号量是不一样的,每个人有每个人关注的信号量

private volatile boolean usedData = true;//mutex for data
private final Lock lock = new ReentrantLock();
private final Condition isEmpty = lock.newCondition();//生产者关心 isEmpty信号量
private final Condition isFull = lock.newCondition(); public void setData(int data) throws InterruptedException {
lock.lock();
try {
while(!usedData) {//wait for data to be used如果数据为没有消费,那么就会阻塞到 isEmpty信号量,生产者等待这个空信号量
isEmpty.await();
}
this.data = data;
isFull.signal();//broadcast that the data is now full. 释放 isFull满这个信号量
usedData = false;//tell others I created new data.
}finally {
lock.unlock();//interrupt or not, release lock
}
} public void getData() throws InterruptedException{
lock.lock();
try {
while(usedData) {//usedData is lingo for empty 这里都必须是循环,因为 从await()这个函数 退出阻塞说明条件可能满足,不是一定满足
isFull.await();
}
isEmpty.signal();//tell the producers to produce some more.
usedData = true;//tell others I have used the data.
}finally {//interrupted or not, always release lock
lock.unlock();
}
}

然后注意信号量和 条件是不一样的东西

if the condition is not true, it calls await(), which atomically unlocks the lock and blocks on the condition variable.

When another thread calls signal() or signalAll() to indicate that the condition might now be true, await() unblocks and automatically reacquires the lock. An important point is that when await() returns, it only indicates that the condition might be true. This is why await() is called within a loop—we need to go back,recheck whether the condition is true, and potentially block on await() again if necessary.

 ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
lock.lock();
try {
while (!<<condition is true>>) //如果条件不满足
condition.await();
<<use shared resources>>
} finally { lock.unlock(); }

然后是具体实例

 private void think() throws InterruptedException {
table.lock();
try {
eating = false;
left.condition.signal();//释放条件变量
right.condition.signal();//释放条件变量
} finally { table.unlock(); }
Thread.sleep(1000);
}
private void eat() throws InterruptedException {
table.lock();
try {
13 while (left.eating || right.eating)
14 condition.await();
eating = true;
} finally { table.unlock(); }
Thread.sleep(1000);
}

java ReentrantLock可重入锁功能的更多相关文章

  1. java ReentrantLock可重入锁的使用场景

    摘要 从使用场景的角度出发来介绍对ReentrantLock的使用,相对来说容易理解一些. 场景1:如果发现该操作已经在执行中则不再执行(有状态执行) a.用在定时任务时,如果任务执行时间可能超过下次 ...

  2. JUC 一 ReentrantLock 可重入锁

    java.util.concurrent.locks ReentrantLock即可重入锁,实现了Lock和Serializable接口 ReentrantLock和synchronized都是可重入 ...

  3. ReenTrantLock可重入锁(和synchronized的区别)总结

    ReenTrantLock可重入锁(和synchronized的区别)总结 可重入性: 从名字上理解,ReenTrantLock的字面意思就是再进入的锁,其实synchronized关键字所使用的锁也 ...

  4. ReentrantLock可重入锁的理解和源码简单分析

    import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** * @author ...

  5. ReenTrantLock可重入锁和synchronized的区别

    ReenTrantLock可重入锁和synchronized的区别 可重入性: 从名字上理解,ReenTrantLock的字面意思就是再进入的锁,其实synchronized关键字所使用的锁也是可重入 ...

  6. Java中可重入锁ReentrantLock原理剖析

    本文由码农网 – 吴极心原创,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! 一. 概述 本文首先介绍Lock接口.ReentrantLock的类层次结构以及锁功能模板类AbstractQue ...

  7. Java多线程——深入重入锁ReentrantLock

    简述 ReentrantLock 是一个可重入的互斥(/独占)锁,又称为“独占锁”. ReentrantLock通过自定义队列同步器(AQS-AbstractQueuedSychronized,是实现 ...

  8. ReentrantLock——可重入锁的实现原理

    一. 概述 本文首先介绍Lock接口.ReentrantLock的类层次结构以及锁功能模板类AbstractQueuedSynchronizer的简单原理,然后通过分析ReentrantLock的lo ...

  9. ReentrantLock可重入锁——源码详解

    开始这篇博客之前,博主默认大家都是看过AQS源码的~什么居然没看过猛戳下方 全网最详细的AbstractQueuedSynchronizer(AQS)源码剖析(一)AQS基础 全网最详细的Abstra ...

随机推荐

  1. jBox使用记录

    1.不显示底部按钮,可以将buttons设置为buttons:{} 例:$.jBox.open("iframe:http://www.baidu.com", "百度一下& ...

  2. android应用程序如何调用支付宝接口

    最近在做一个关于购物商城的项目,项目里面付款这块我选的是调用支付宝的接口,因为用的人比较多. 在网上搜索了以下,有很多这方面的教程,但大部分教程过于陈旧,而且描述的过于简单.而且支付宝提供的接口一直在 ...

  3. windows加入path路径

    右键我的电脑,属性:高级系统设置,高级,环境变量:在系统变量中选path,编辑:将python安装路径加入即可(注意分号):

  4. POJ 3349 HASH

    题目链接:http://poj.org/problem?id=3349 题意:你可能听说话世界上没有两片相同的雪花,我们定义一个雪花有6个瓣,如果存在有2个雪花相同[雪花是环形的,所以相同可以是旋转过 ...

  5. Eclipse快捷键/快捷操作汇总

    1.建立.切换不同的工作空间: 工作空间是放置项目的,它是项目的集合,多个工程放在一个工作空间上容易出问题,建议把不同项目存放在单独的工作  空间内,让项目代码更加有序 file → switch w ...

  6. POJ1637 Sightseeing tour(判定混合图欧拉回路)

    有向连通图存在欧拉回路的充要条件是所有点入度=出度. 首先随便给定所有无向边一个方向(不妨直接是u->v方向),记录所有点的度(记:度=入度-出度). 这时如果有点的度不等于0,那么就不存在欧拉 ...

  7. 每天一个linux命令---curl

    linux curl是一个利用URL规则在命令行下工作的文件传输工具.详细请参考:http://www.codesky.net/article/201010/170043.html 例如:curl ' ...

  8. java-嵌套类

    浏览以下内容前,请点击并阅读 声明 java允许在一个类中定义另外一个类,这就叫类嵌套.类嵌套分为两种,静态的称为静态嵌套类,非静态的又称为内部类. 使用嵌套类的原因: 能够将仅在一个地方使用的类合理 ...

  9. WPF [调用线程无法访问此对象,因为另一个线程拥有该对象。] 解决方案以及如何实现字体颜色的渐变

    本文说明WPF [调用线程无法访问此对象,因为另一个线程拥有该对象.] 解决方案以及如何实现字体颜色的渐变 先来看看C#中Timer的简单说明,你想必猜到实现需要用到Timer的相关知识了吧. C# ...

  10. iOS学习05C语言函数

    本次主要是学习和理解函数,函数树状图如下: 1.函数的声明和定义 函数定义的四要素分别为: 返回值类型 :函数的结果值类型,函数不能返回数组. 指定返回类型是void类型说明函数没有返回值. 函数名 ...