ReentrantLock 介绍
ReentrantLock 是一个可重入且独占式的锁,它具有与使用 synchronized 监视器锁相同的基本行为和语义,但与 synchronized 关键字相比,它更灵活、更强大。
使用示例
public class Test {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private int count;
public void add() {
lock.lock();
try {
while (count != 0) {
condition.await();
}
count ++;
System.out.println("加加");
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void subtract() {
lock.lock();
try {
while (count == 0) {
condition.await();
}
count --;
System.out.println("减减");
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws Exception{
Test t = new Test();
new Thread(()->{
for(int i=0; i<100; i++)
t.add();
}).start();
new Thread(()->{
for(int i=0; i<100; i++)
t.subtract();
}).start();
}
}
结果:
加加
减减
加加
减减
......
构造方法
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}