java ReentrantLock
介绍
ReentrantLock称为重入锁,比内部锁synchonized拥有更强大的功能,它可中断、可定时、设置公平锁
【注】使用ReentrantLock时,一定要释放锁,一般释放放到finnal里写。
提供以下重要的方法
- lock():获得锁,如果锁已被占用,则等待
- lockInterruptibly():获得锁,但有限响应中断
- unlock():释放锁
- tryLock():尝试获取锁。如果获得,返回true;否则返回false
- 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]ReentrantLock重入锁
图解ReentrantLock 0. demo 我先给出一个demo, 这样大家就可以根据我给的这段代码, 边调试边看源码了. 还是那句话: 注意"My" , 我把Reentran ...
- java ReentrantLock 公平锁 非公平锁 测试
package reentrantlock; import java.util.ArrayList; import java.util.concurrent.locks.ReentrantLock; ...
- java ReentrantLock结合条件队列 实现生产者-消费者模式 以及ReentratLock和Synchronized对比
package reentrantlock; import java.util.ArrayList; public class ProviderAndConsumerTest { static Pro ...
- JAVA REENTRANTLOCK、SEMAPHORE 的实现与 AQS 框架
引言 ReentrantLock是JDK提供的一个可重入互斥锁,所谓可重入就是同一个锁允许被已经获得该锁的线程重新获得.可重入锁的好处可以在递归算法中使用锁,不可重入锁则导致无法在递归算法中使用锁.因 ...
- Java ReEntrantLock 之 Condition条件(Java代码实战-002)
import java.util.LinkedList; import java.util.concurrent.locks.Condition; import java.util.concurren ...
- Java ReEntrantLock (Java代码实战-001)
Lock类也可以实现线程同步,而Lock获得锁需要执行lock方法,释放锁需要执行unLock方法 Lock类可以创建Condition对象,Condition对象用来使线程等待和唤醒线程,需要注意的 ...
- Java ReentrantLock和synchronized两种锁定机制的对比
多线程和并发性并不是什么新内容,但是 Java 语言设计中的创新之一就是,它是第一个直接把跨平台线程模型和正规的内存模型集成到语言中的主流语言.核心类库包含一个 Thread 类,可以用它来构建.启动 ...
- java ReentrantLock可重入锁功能
1.可重入锁是可以中断的,如果发生了死锁,可以中断程序 //如下程序出现死锁,不去kill jvm无法解决死锁 public class Uninterruptible { public static ...
- java ReentrantLock Condition
sychronized.wait.notify.notifyAll.sleep 在多线程环境下,为了防止多个线程同时调用同一个方法.修改同一份变量,造成数据读取结果混乱,可以使用synchronize ...
随机推荐
- appium解决每次运行都需要安装Unlock以及AppiumSetting的问题
这是我用appium遇到的第三个坑?之前因为环境的问题,chromedriver驱动总是安装不对,后来发现是因为路径的原因.解决之后,现在出现新的问题,那就是“appium每次运行都要去重新安装Unl ...
- linux五种I/O模型
1.基本概念 1.1同步和异步 同步和异步关注的是消息通信机制 1.1.1同步 所谓同步,就是在发出一个调用时,在没有得到结果之前,调用就不返回,一直在等,但是一旦调用返回,就能得到返回值. 1.1. ...
- es6剩余参数
function show(a,b,...args){ console.log(a) console.log(b) console.log(args) } show(10,20,30,30,36)
- 第二次OO总结
作业5——多线程电梯 好像失忆了,竟然对这三部电梯很陌生,我尽量回忆一下当时挣扎的场景orz 整体思路和第二次电梯差不多,但是将调度器类套在了电梯类里 优点可能是没有无效,足矣!!!缺点emmmm要是 ...
- 实践中 XunSearch(讯搜)更新索引方案对比
检测PHP-SDK的运行条件(查看是否支持XunSearch) $prefix/sdk/php/util/RequiredCheck.php $prefix #替换成你的安装目录 使用 XunSe ...
- 在原生Windows安装Keras
既然要深入学习,就不能和时代脱节,所以选择了keras,资源相对比较丰富.由于Windows饱受歧视,各种文档都不推荐使用.但我又没有换系统的成本,所以还是凑合下,毕竟他们给出了方法,稍微折腾一下还是 ...
- 网络编程 —— UPD
UDP协议(数据报协议:SOCK_DGRAM) udp是无链接的,先启动哪一端都不会报错 udp协议的特点: 传输数据不可靠,发送完后没有确认就删除 传送内容可为空 对于查寻速度快 支持的是一对多的模 ...
- Apache Tomcat Eclipse Integration
An Illustrated Quick Start Guide Apache Tomcat makes hosting your applications easy. The Eclipse IDE ...
- 你不知道的 #include
1.#include 指令 C++的程序中带 “#” 号的语句被称为宏定义或编译指令.#include在代码中是包含和引用的意思,例如:"#include <iostream>& ...
- FPGA中分数分频器的实现代码
module clkFracDiv( output reg clkout, input rstn, input refclk, :] fenzi, :] fenmu ); :] rstn_syn; : ...