标签:
ReentrantLock 与 synchronized 相比主要特性:1.等候时间锁;
2.可中断锁;
3.多个条件变量;
等候时间锁实现主要通过 reentrantlock.tryLock(5,TimeUnit.SECONDS)方法实现;
多个条件变量可通过reentrantlock.newCondition() new出多个实例实现;可中断锁在BlockingQueue中经常被用到,简单通过代码理解
package net.flyingfat.lock;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ReenLock2 {
ReentrantLock lock=new ReentrantLock();
Condition condition1=lock.newCondition();
public static void main(String[] args) {
final ReenLock2 reenLock2=new ReenLock2();
Thread t=new Thread(new Runnable() {
public void run() {
reenLock2.run(); //切换run1(),run2()
}
});
t.start();
Thread t1=new Thread(new Runnable() {
public void run() {
reenLock2.run(); //切换run1(),run2()
}
});
t1.start();
try {
Thread.sleep(1000);
t1.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run(){
try{
lock.lockInterruptibly(); //可中断锁
System.out.println("thread:"+Thread.currentThread().getName()+" get lock");
Thread.sleep(4000);
System.out.println("thread:"+Thread.currentThread().getName()+" wake up");
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("thread:"+Thread.currentThread().getName()+" release lock");
lock.unlock();
}
}
public void run1(){
try{
lock.lock(); //ReentrantLock实现的常规锁
System.out.println("thread:"+Thread.currentThread().getName()+" get lock");
Thread.sleep(4000);
System.out.println("thread:"+Thread.currentThread().getName()+" wake up");
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("thread:"+Thread.currentThread().getName()+" release lock");
lock.unlock();
}
}
public synchronized void run2(){ //synchronized 实现的常规锁
try {
System.out.println("thread:"+Thread.currentThread().getName()+" get lock");
Thread.sleep(4000);
System.out.println("thread:"+Thread.currentThread().getName()+" release lock");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run3(){
try{
lock.tryLock(5,TimeUnit.SECONDS); //等候锁
System.out.println("thread:"+Thread.currentThread().getName()+" get lock");
Thread.sleep(4000);
System.out.println("thread:"+Thread.currentThread().getName()+" wake up");
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("thread:"+Thread.currentThread().getName()+" release lock");
lock.unlock();
}
}
}
0号线程和1号线程共同调用run()方法时,0号线程率先获得锁,进入4秒的休眠, 同时1号线程正在等待获取锁,当主线程对1号线程调用interrupt方法时,1号线程立即终止等待。
0号线程和1号线程共同调用run()1方法时,0号线程率先获得锁,进入4秒的休眠, 同时1号线程正在等待获取锁,当主线程对1号线程调用interrupt方法时,1号线程并没有立即终止,而是等待0号线程执行完毕,1号线程调用sleep方法时抛出终止异常。
run2和run1雷同,用synchronized 实现。这也反映 了synchronized 同步不能实现对等待中的线程实现中断操作。
ReentrantLock 与 synchronized 一点区别
标签:
原文地址:http://blog.csdn.net/zhuyijian135757/article/details/51347935