net.lulihu.lock.OrderExecuteLockKit Maven / Gradle / Ivy
package net.lulihu.lock;
import lombok.extern.slf4j.Slf4j;
import net.lulihu.dataStructure.LRULinkedHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 按序执行锁工具
*
* 请注意如果应该先执行的方法因为线程池当前的执行队列全部被靠后的占用,将导致产生死锁
*
* 使用方式如下:
*
* import ConditionLock;
* import OrderExecuteLockKit;
*
* import java.util.concurrent.ExecutorService;
* import java.util.concurrent.Executors;
*
* public class Test {
*
* public static void main(String[] args) {
* OrderExecuteLockKit executeLockKit = new OrderExecuteLockKit();
* ExecutorService pool = Executors.newFixedThreadPool(3);
*
* Run run1 = new Run(executeLockKit.getConditionLock(), "1");
* Run run2 = new Run(executeLockKit.getConditionLock(), "2");
* Run run3 = new Run(executeLockKit.getConditionLock(), "3");
*
* pool.execute(run3);
* pool.execute(run2);
* pool.execute(run1);
* }
*
* public static class Run implements Runnable {
*
* private final ConditionLock conditionLockKit;
*
* private final String mes;
*
* public Run(ConditionLock conditionLockKit, String mes) {
* this.conditionLockKit = conditionLockKit;
* this.mes = mes;
* }
*
* public void run() {
* try {
* conditionLockKit.getLock();
* System.out.println(mes);
* } finally {
* conditionLockKit.unlock();
* }
* }
* }
*
*/
@Slf4j
public class OrderExecuteLockKit {
/**
* 可重入锁
*/
private final ReentrantLock lock;
/**
* 信号增量
*/
private final AtomicInteger incrementalSignal;
/**
* 增量信号映射对象`线程安全的LinkedHashMap
*/
private final LRULinkedHashMap incrementalSignalMap;
public OrderExecuteLockKit() {
this.lock = new ReentrantLock();
this.incrementalSignal = new AtomicInteger(0);
this.incrementalSignalMap = new LRULinkedHashMap<>();
}
/**
* 获取条件锁对象,对执行线程进行按序执行
*
* 优先获取到条件锁的对象,将优先执行
*
* @return 条件锁对象
*/
public synchronized ConditionLock getConditionLock() {
int incremental = incrementalSignal.incrementAndGet();
Condition condition = lock.newCondition();
incrementalSignalMap.put(incremental, condition);
return new ConditionLock(incremental, condition, this);
}
/**
* 获取锁
*/
void getLock() {
lock.lock();
}
/**
* 释放锁
*/
void unlock() {
lock.unlock();
}
/**
* 获取增量信号映射对象 LRULinkedHashMap
*
* @return 增量信号映射对象 LRULinkedHashMap
*/
LRULinkedHashMap getIncrementalSignalMap() {
return incrementalSignalMap;
}
}