ReentrantLock与synchronized相同点
都是独占锁,并且都可重入,通过以下代码可以证明ReentrantLock支持重入
public class ReentrantLock_T1 {
Lock lock = new ReentrantLock();
void m1() {
lock.lock();
try {
for(int i = 0; i < 10; i++) {
System.out.println(i);
TimeUnit.SECONDS.sleep(1);
m2();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
void m2() {
lock.lock();
try {
System.out.println("m2");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLock_T1 r = new ReentrantLock_T1();
new Thread(r::m1).start();
}
}
ReentrantLock与synchronized不同点
- ReentrantLock需要手动加锁与解锁,并且在重入时,加锁解锁的数量要一致,synchronized加锁解锁的过程是隐式的,不用手动操作。
- ReentrantLock更灵活,例如支持公平锁,公平锁是指当锁可用时,在锁上等待时间最长的线程将获得锁的使用权
ReentrantLock实现公平锁
public class ReentrantLock_T2 {
ReentrantLock lock = new ReentrantLock(true);
void m1() {
for(int i = 0; i < 100; i++) {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "拿到锁");
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
ReentrantLock_T2 t2 = new ReentrantLock_T2();
new Thread(t2::m1).start();
new Thread(t2::m1).start();
}
}