add:添加锁工具

This commit is contained in:
zhangzq
2024-12-17 09:40:41 +08:00
parent b2cf0fc3c5
commit c30b60ed92

View File

@@ -0,0 +1,64 @@
package org.nl.acs.utils;
import org.nl.common.exception.BadRequestException;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
public class LockUtils {
private static ConcurrentHashMap<String, ReentrantLock> locks = new ConcurrentHashMap<>();
public static <T> T lock(String key, Supplier<T> supplier,Integer second) {
ReentrantLock lock;
synchronized (key.intern()){
lock = locks.get(key);
if (lock==null){
lock = new ReentrantLock();
locks.put(key, lock) ;
}
}
boolean isLock = false;
if (second !=null){
try {
isLock = lock.tryLock(second, TimeUnit.SECONDS);
}catch (Exception ex){
isLock = false;
}
}else {
isLock = lock.tryLock();
}
try {
if (isLock){
return supplier.get();
}else {
throw new BadRequestException(Thread.currentThread().getName()+"当前业务"+key+"正在执行");
}
}catch (Exception ex){
throw new BadRequestException(Thread.currentThread().getName()+"当前业务"+key+"正在执行");
}finally {
if (lock.isLocked() && lock.isHeldByCurrentThread()){
lock.unlock();
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(()->{
String key = String.valueOf(new Random().nextInt(5));
String result = LockUtils.lock(key, () -> {
try {
System.out.println(Thread.currentThread().getName() + "正在执行");
Thread.sleep(2000);
} catch (Exception ex) {
}
return key;
}, null);
System.out.println("执行结果"+result);
}).start();
}
}
}