目录
-
ReentrantLock的API介绍
-
Condition的API介绍
-
ReentrantLock的使用实例
一、ReentrantLock的API介绍
ReentrantLock reentrantLock = new ReentrantLock();
/**
* 获取锁,如果获取不到锁, 则一直阻塞
*/
reentrantLock.lock();
/**
* 获取锁, 线程在持有锁和阻塞获取锁的时候, interrupt会跑出异常
*/
try {
reentrantLock.lockInterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 尝试获取锁, 如果获取不到锁则立即返回, 获取到锁返回true, 获取不到锁返回false
*/
reentrantLock.tryLock();
/**
* 在指定时间内获取锁, 如果获取不到则返回false; 在阻塞期间执行interrupt, 则会抛出异常
*/
try {
reentrantLock.tryLock(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 释放锁
*/
reentrantLock.unlock();
/**
* 创建公平锁
*/
ReentrantLock reentrantLock1 = new ReentrantLock(true);
/**
* 查看有多少线程等待锁
*/
int num = reentrantLock.getQueueLength();
/**
* 查看是否有线程等待抢锁
*/
boolean boolean1 = reentrantLock.hasQueuedThreads();
/**
* 指定线程是否持有锁
*/
boolean boolean2 = reentrantLock.hasQueuedThread(new Thread());
/**
* 当前线程是否抢到锁, 返回0则代表没有
*/
int num2 = reentrantLock.getHoldCount();
/**
* 查询此锁是否有任何线程持有
*/
boolean boolean3 = reentrantLock.isLocked();
/**
* 是否为公平锁
*/
boolean boolean4 = reentrantLock.isFair();
/**
* 返回锁的条件Condition
*/
Condition condition = reentrantLock.newCondition();
二、Condition的API介绍
/**
* 返回锁的条件Condition
*/
Condition condition = reentrantLock.newCondition();
/**
* 执行等待, 可允许中断
*/
try {
condition.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 执行等待, 不允许中断
*/
condition.awaitUninterruptibly();
/**
* 执行等待, 单位为纳秒, 阻塞中可允许中断, 返回值大于零表示被唤醒, 小于零表示超时
*/
try {
long long1 = condition.awaitNanos(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 类似awaitNanos
*/
try {
boolean boolean5 = condition.awaitUntil(new Date());
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 唤醒等待中的一个线程
*/
condition.signal();
/**
* 唤醒等待中的所有线程
*/
condition.signalAll();
三、ReentrantLock的使用实例
/**
* 此实例为两个线程交替打印0-26的阿拉伯数字和26个英文字母, 其他案例可以此进行扩展
*/
ReentrantLock reentrantLock = new ReentrantLock();
Condition condition1 = reentrantLock.newCondition();
Condition condition2 = reentrantLock.newCondition();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
try {
for (int i = 65; i < 91; i++) {
System.out.println(Thread.currentThread().getName() + "---------------" + (char)i);
condition2.signal();
condition1.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
reentrantLock.unlock();
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
try {
for (int i = 0; i < 26; i++) {
System.out.println(Thread.currentThread().getName() + "---------------" + i);
condition1.signal();
condition2.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
reentrantLock.unlock();
}
}
});
thread2.start();
如想深入了解内部原理,请参考源码