add:添加锁的工具类
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package org.nl.acs.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class CurrentLock {
|
||||
|
||||
static ConcurrentHashMap<String, ReentrantLock> clock = new ConcurrentHashMap<>();
|
||||
static Timer timer = new Timer(true);
|
||||
|
||||
public static Boolean tryLock(String key){
|
||||
synchronized (buildLock(key)){
|
||||
ReentrantLock lock = clock.get(key);
|
||||
if (lock == null){
|
||||
ReentrantLock reentrantLock = new ReentrantLock();
|
||||
clock.put(key,reentrantLock);
|
||||
return reentrantLock.tryLock();
|
||||
}else {
|
||||
return lock.tryLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
public static void unLock(String key){
|
||||
System.out.println("---释放锁---");
|
||||
synchronized (buildLock(key)){
|
||||
ReentrantLock lock = clock.get(key);
|
||||
if (lock != null){
|
||||
if (lock.isLocked() && lock.isHeldByCurrentThread()){
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private static String buildLock(String key) {
|
||||
if (StrUtil.isEmpty(key)) {
|
||||
key = "";
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("currentLock.");
|
||||
builder.append(key);
|
||||
String lock = builder.toString().intern();
|
||||
return lock;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user