它比内部锁synchronized拥有更加强大的功能,他可以中断、定时。它提供了著名的公平锁和非公平锁
公平锁和非公平锁
- 公平锁:获取不到锁的时候,会自动加入队列,等待线程释放后,队列的第一个线程获取锁
- 非公平锁:获取不到锁的时候,会自动加入队列,等待线程释放锁后,所有等待的线程同时去竞争
性能上,非公平锁的性能要好得多,如果没有特殊要求,优先考虑非公平锁
public ReentrantLock(boolean fair) //fair决定是否为公平锁
下面是简单的ReentrantLock代码使用方法:
模拟了first 线程和second线程相互争夺锁的代码:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class test {
ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
test test = new test();
Thread first = new Thread(test.createTask(), " FirstThread");
Thread second = new Thread(test.createTask(), " SecondThread");
first.start();
second.start();
Thread.sleep(600);
second.interrupt();
}
private Runnable createTask(){
return new Runnable(){
@Override
public void run() {
while (true){
try {
if (lock.tryLock(500, TimeUnit.MILLISECONDS)){
try {
System.out.println("locked" + Thread.currentThread().getName());
Thread.sleep(1000);
}finally {
lock.unlock();
System.out.println("unlocked " + Thread.currentThread().getName());
}
break;
} else {
System.out.println("unable to lock " + Thread.currentThread().getName());
}
}catch (InterruptedException e){
System.out.println(Thread.currentThread().getName() + "is Interrupted");
}
}
}
};
}
}
重要的方法
- tryLock(500, TimeUnit.MILLISECONDS) : 上面代码展示了等待500ms的效果
- lock():获得锁,如果锁已经被占用,则等待
- lockInterruptible():获得锁,但优先响应中断
- tryLock():尝试获得锁,成功返回true,否则返回false,不等待
- unlock():释放锁