From c30b60ed9206ac72084499a8089116f29c0c9f9f Mon Sep 17 00:00:00 2001 From: zhangzq Date: Tue, 17 Dec 2024 09:40:41 +0800 Subject: [PATCH] =?UTF-8?q?add:=E6=B7=BB=E5=8A=A0=E9=94=81=E5=B7=A5?= =?UTF-8?q?=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/org/nl/acs/utils/LockUtils.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/LockUtils.java diff --git a/acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/LockUtils.java b/acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/LockUtils.java new file mode 100644 index 0000000..688cdb1 --- /dev/null +++ b/acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/LockUtils.java @@ -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 locks = new ConcurrentHashMap<>(); + public static T lock(String key, Supplier 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(); + } + } +} +