ReentrantLock 是jdk1.5之后,并发包中新增了Lock接口(以及相关实现类)用来实现锁的功能,它提供了与synchronized关键字类似的同步功能。
相比synchronized,多了以下功能:
- 等待过程可中断
- 可实现公平锁
- 可绑定多个条件
相比synchronized 之间的差异:
- synchronized是JVM实现的,ReentrantLock是JDK实现的
- ReentrantLock多了些高级功能,使用起来更灵活一些,但是需要注意死锁问题。而synchronized 则不用担心没有释放锁导致死锁的问题(JVM会保证锁的释放)。
用例代码:
package cn.zealon.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 重入锁用例
*/
public class UseReentrantLock implements Runnable {
private Lock lock = new ReentrantLock();
public void func(){
lock.lock();
System.out.println("
"+Thread.currentThread().getName());
try{
for(int i=0;i<10;i++){
System.out.print(" "+i);
}
} finally {
lock.unlock();
}
}
@Override
public void run() {
func();
}
public static void main(String[] args){
UseReentrantLock useReentrantLock = new UseReentrantLock();
//UseReentrantLock useReentrantLock2 = new UseReentrantLock();
Thread t1 = new Thread(useReentrantLock);
Thread t2 = new Thread(useReentrantLock);
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(t1);
executorService.execute(t2);
executorService.shutdown();
}
}
输出结果(保证了线程1执行完,再执行线程2):
pool-1-thread-1
0 1 2 3 4 5 6 7 8 9
pool-1-thread-2
0 1 2 3 4 5 6 7 8 9
不加锁的输出结果(每次不一样):
pool-1-thread-1
pool-1-thread-2
0 1 2 3 4 5 0 6 1 7 2 3 4 5 8 6 9 7 8 9
作者: Zealon
崇尚简单,一切简单自然的事物都是美好的。