import java.util.concurrent.locks.ReentrantLock;
/**
* Created by haicheng.lhc on 17/05/2017.
*
* @author haicheng.lhc
* @date 2017/05/17
*/
public class ReentrantLockTest extends Thread {
public static ReentrantLock lock = new ReentrantLock();
public static int i = 0;
public ReentrantLockTest(String name) {
super.setName(name);
}
@Override
public void run() {
for (int j = 0; j < 10000000; j++) {
lock.lock();
try {
System.out.println(this.getName() + " " + i);
i++;
} finally {
lock.unlock();
}
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
ReentrantLockTest test1 = new ReentrantLockTest("thread1");
ReentrantLockTest test2 = new ReentrantLockTest("thread2");
test1.start();
test2.start();
test1.join();
test2.join();
System.out.println(i);
}
}
ReenTrantCock的优点是比较灵活但使用麻烦。需要finally代码块中解锁。
- java中已经有了内置锁:
synchronized
,synchronized
的特点是使用简单,一切交给JVM去处理,不需要显示释放 - 从用法上可以看出,与
synchronized
相比,ReentrantLock
就稍微复杂一点。因为必须在finally中进行解锁操作,如果不在 finally解锁,有可能代码出现异常锁没被释放, -
那么为什么要引入ReentrantLock呢?
- 在jdk1.5里面,
ReentrantLock
的性能是明显优于synchronized
的,但是在jdk1.6里面,synchronized
做了优化,他们之间的性能差别已经不明显了。 ReentrantLock
并不是一种替代内置加锁的方法,而是作为一种可选择的高级功能。- 相比于
synchronized
,ReentrantLock
在功能上更加丰富,它具有可重入、可中断、可限时、公平锁等特点。