ReentrantLock介绍
ReentrantLock是一个可重入的互斥锁,又被称为“独占锁”。
顾名思义,ReentrantLock锁在同一个时间点只能被一个线程锁持有;而可重入的意思是,ReentrantLock锁,可以被单个线程多次获取。
ReentrantLock分为“公平锁”和“非公平锁”。它们的区别体现在获取锁的机制上是否公平。“锁”是为了保护竞争资源,防止多个线程同时操作线程而出错,ReentrantLock在同一个时间点只能被一个线程获取(当某线程获取到“锁”时,其它线程就必须等待);ReentraantLock是通过一个FIFO的等待队列来管理获取该锁所有线程的。在“公平锁”的机制下,线程依次排队获取锁;而“非公平锁”在锁是可获取状态时,不管自己是不是在队列的开头都会获取锁。
ReentrantLock函数列表
// 创建一个 ReentrantLock ,默认是“非公平锁”。
ReentrantLock()
// 创建策略是fair的 ReentrantLock。fair为true表示是公平锁,fair为false表示是非公平锁。
ReentrantLock(boolean fair)
// 查询当前线程保持此锁的次数。
int getHoldCount()
// 返回目前拥有此锁的线程,如果此锁不被任何线程拥有,则返回 null。
protected Thread getOwner()
// 返回一个 collection,它包含可能正等待获取此锁的线程。
protected Collection<Thread> getQueuedThreads()
// 返回正等待获取此锁的线程估计数。
int getQueueLength()
// 返回一个 collection,它包含可能正在等待与此锁相关给定条件的那些线程。
protected Collection<Thread> getWaitingThreads(Condition condition)
// 返回等待与此锁相关的给定条件的线程估计数。
int getWaitQueueLength(Condition condition)
// 查询给定线程是否正在等待获取此锁。
boolean hasQueuedThread(Thread thread)
// 查询是否有些线程正在等待获取此锁。
boolean hasQueuedThreads()
// 查询是否有些线程正在等待与此锁有关的给定条件。
boolean hasWaiters(Condition condition)
// 如果是“公平锁”返回true,否则返回false。
boolean isFair()
// 查询当前线程是否保持此锁。
boolean isHeldByCurrentThread()
// 查询此锁是否由任意线程保持。
boolean isLocked()
// 获取锁。
void lock()
// 如果当前线程未被中断,则获取锁。
void lockInterruptibly()
// 返回用来与此 Lock 实例一起使用的 Condition 实例。
Condition newCondition()
// 仅在调用时锁未被另一个线程保持的情况下,才获取该锁。
boolean tryLock()
// 如果锁在给定等待时间内没有被另一个线程保持,且当前线程未被中断,则获取该锁。
boolean tryLock(long timeout, TimeUnit unit)
// 试图释放此锁。
void unlock()
ReentrantLock示例--生产者与消费者模式
示例一:无锁情况
//实体类 -- 汽车工厂,包含属性:厂家名称,产品数量
package entity;
/**
* Created by zongx on 2019/10/22.
*/
public class CarFactory {
private String name;
public int size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
生产者与消费者:
/**
* Created by zongx on 2019/10/22.
*/
public class Producer implements Runnable {
private CarFactory factory ;
private String name;
private ReentrantLock lock;
public Producer(CarFactory factory, String name, ReentrantLock lock) {
this.factory = factory;
this.name = name;
this.lock = lock;
}
private void produce(){
int size = factory.getSize();
System.out.println(this.name + "生产到" + factory.getName()+ "当前数量:" + (size+1));
factory.setSize(++size);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
produce();
}
}
}
/**
* Created by zongx on 2019/10/22.
*/
public class Consumer implements Runnable {
private CarFactory factory ;
private String name;
private ReentrantLock lock;
public Consumer(CarFactory factory, String name, ReentrantLock lock) {
this.factory = factory;
this.name = name;
this.lock = lock;
}
private void consume(){
int size = factory.getSize();
System.out.println(this.name + "消费了" + factory.getName()+ "当前数量:" + (size-1));
factory.setSize(--size);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
consume();
}
}
}
测试结果:
生产者生产100个,消费者消费100,看最后结果:
package lock.ReentrantLock;
import entity.CarFactory;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by zongx on 2019/10/22.
*/
public class Demo {
public static void main(String[] args) throws InterruptedException {
CarFactory carFactory = new CarFactory();
ReentrantLock lock = new ReentrantLock();
carFactory.setName("汽车工厂");
Producer producer = new Producer(carFactory, "工厂-----",lock);
Consumer consumer = new Consumer(carFactory, "销售商------", lock);
new Thread(producer).start();
new Thread(consumer).start();
}
}
多线程处理,无法预知最后结果是什么。
示例二:加入锁
生产者与消费者:
package lock.ReentrantLock;
import entity.CarFactory;
import lock.reentrantSpinLock.ReentrantSpinLock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by zongx on 2019/10/22.
*/
public class Consumer implements Runnable {
private CarFactory factory ;
private String name;
private ReentrantLock lock;
public Consumer(CarFactory factory, String name, ReentrantLock lock) {
this.factory = factory;
this.name = name;
this.lock = lock;
}
private void consume(){
lock.lock();
int size = factory.getSize();
System.out.println(this.name + "消费了" + factory.getName()+ "当前数量:" + (size-1));
factory.setSize(--size);
lock.unlock();
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
consume();
}
}
}
package lock.ReentrantLock;
import entity.CarFactory;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by zongx on 2019/10/22.
*/
public class Producer implements Runnable {
private CarFactory factory ;
private String name;
private ReentrantLock lock;
public Producer(CarFactory factory, String name, ReentrantLock lock) {
this.factory = factory;
this.name = name;
this.lock = lock;
}
private void produce(){
lock.lock();
int size = factory.getSize();
System.out.println(this.name + "生产到" + factory.getName()+ "当前数量:" + (size+1));
factory.setSize(++size);
lock.unlock();
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
produce();
}
}
}
结果:
最终结果能够保证为0,但中间会出现负数情况:
示例三:加入Condition,进行生产者与消费者线程间消息传递
Condition的强大之处在于它可以为多个线程间建立不同的Condition, 使用synchronized/wait()只有一个阻塞队列,notifyAll会唤起所有阻塞队列下的线程,而使用lock/condition,可以实现多个阻塞队列,signalAll只会唤起某个阻塞队列下的阻塞线程。
//实体类增加属性,最大数量
package entity;
/**
* Created by zongx on 2019/10/22.
*/
public class CarFactory {
private String name;
public int size;
private int maxSize = 10;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
}
生产者与消费者:
package lock.ReentrantLock;
import entity.CarFactory;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by zongx on 2019/10/22.
*/
public class Producer implements Runnable {
private CarFactory factory ;
private String name;
private ReentrantLock lock;
private Condition notFull ;
private Condition notEmpty ;
public Producer(CarFactory factory, String name, ReentrantLock lock,Condition notFull ,Condition notEmpty) {
this.factory = factory;
this.name = name;
this.lock = lock;
this.notFull = notFull;
this.notEmpty = notEmpty;
}
private void produce() throws InterruptedException {
lock.lock();
while (factory.getSize() == factory.getMaxSize()) {
notFull.await();
}
int size = factory.getSize();
System.out.println(this.name + "生产到" + factory.getName()+ " ;当前数量:" + (size+1));
factory.setSize(++size);
notEmpty.signalAll();
lock.unlock();
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
produce();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package lock.ReentrantLock;
import entity.CarFactory;
import lock.reentrantSpinLock.ReentrantSpinLock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by zongx on 2019/10/22.
*/
public class Consumer implements Runnable {
private CarFactory factory ;
private String name;
private ReentrantLock lock;
private Condition notFull ;
private Condition notEmpty ;
public Consumer(CarFactory factory, String name, ReentrantLock lock,Condition notFull ,Condition notEmpty) {
this.factory = factory;
this.name = name;
this.lock = lock;
this.notFull = notFull;
this.notEmpty = notEmpty;
}
private void consume() throws InterruptedException {
lock.lock();
while(factory.getSize() == 0){
notEmpty.await();
}
int size = factory.getSize();
System.out.println(this.name + "消费了" + factory.getName()+ " ;当前数量:" + (size-1));
factory.setSize(--size);
notFull.signalAll();
lock.unlock();
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
consume();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
测试与结果:4个代工厂,4个经销商,工厂仓库最多能承受10个。
package lock.ReentrantLock;
import entity.CarFactory;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by zongx on 2019/10/22.
*/
public class Demo {
public static void main(String[] args) throws InterruptedException {
CarFactory carFactory = new CarFactory();
ReentrantLock lock = new ReentrantLock();
Condition notFull = lock.newCondition();
Condition notEmpty = lock.newCondition();
carFactory.setName("汽车工厂");
Producer producer1 = new Producer(carFactory, "代工厂1-----",lock, notFull, notEmpty);
Consumer consumer1 = new Consumer(carFactory, "销售商1------", lock, notFull, notEmpty);
Producer producer2 = new Producer(carFactory, "代工厂2-----",lock, notFull, notEmpty);
Consumer consumer2 = new Consumer(carFactory, "销售商2------", lock, notFull, notEmpty);
Producer producer3 = new Producer(carFactory, "代工厂3-----",lock, notFull, notEmpty);
Consumer consumer3 = new Consumer(carFactory, "销售商3------", lock, notFull, notEmpty);
Producer producer4 = new Producer(carFactory, "代工厂4-----",lock, notFull, notEmpty);
Consumer consumer4 = new Consumer(carFactory, "销售商4------", lock, notFull, notEmpty);
new Thread(producer1).start();
new Thread(consumer1).start();
new Thread(producer2).start();
new Thread(consumer2).start();
new Thread(producer3).start();
new Thread(consumer3).start();
new Thread(producer4).start();
new Thread(consumer4).start();
}
}
- 当生产者执行put方法时,调用notEmpty.signalAll()只会唤醒notEmpty.await()下的消费者线程。
- 当消费者执行塔克方法时,调用notFull.signalAll()只会唤醒notFull.await()下的消费者线程。