T100738
2024-04-16 eeb86aaf2f73a02600195ce2637dde6caf858a88
product-server-data-center/src/main/java/com/product/data/center/utils/CustomLock.java
@@ -1,11 +1,15 @@
package com.product.data.center.utils;
import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.product.core.spring.context.SpringMVCContextHolder;
import org.apache.commons.lang3.StringUtils;
import javax.swing.*;
import java.text.DateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -19,6 +23,7 @@
   private Map<String, Long> obj = new ConcurrentHashMap<>();
   private Map<String, Long> threadObj = new ConcurrentHashMap<>();
   private long detectionWaitTime = 1000L;
@@ -41,12 +46,64 @@
      return this.tryLock(ArrayUtil.join(key, ","));
   }
   public static void main(String[] args) {
      long timemillis = 1709654400039L;
      //转换为年月日时分秒
      String format = DateUtil.format(DateUtil.date(timemillis), "yyyy-MM-dd HH:mm:ss");
      System.out.println(format);
   }
   public boolean tryLock(String key, long timeoutMinute) {
      if (!StringUtils.isEmpty(key)) {
         key = key.toUpperCase();
         synchronized (key.intern()) {
            if (!this.obj.containsKey(key)) {
               lock(key);
               //获取当前线程
               long id = Thread.currentThread().getId();
               threadObj.put(key, id);
               return true;
            } else if (timeoutMinute > 0) {
               //获取锁进入开始时间
               long startTime = obj.get(key);
               //获取当前时间
               long currentTime = System.currentTimeMillis();
               //将分钟转换为毫秒
               long timeout = timeoutMinute * 60 * 1000;
               //如果当前时间减去开始时间大于等于超时时间
               if (currentTime - startTime >= timeout) {
                  long threadId = threadObj.get(key);
                  //根据线程id获取线程
                  Thread[] threads = ThreadUtil.getThreads();
                  for (Thread thread : threads) {
                     if (thread.getId() == threadId) {
                        //中断线程
                        ThreadUtil.interrupt(thread, true);
                        SpringMVCContextHolder.getSystemLogger().error("线程:" + thread.getName() + "超时被中断");
                        return tryLock(key, timeoutMinute);
                     }
                  }
                  return true;
               }
            }
         }
      }
      return false;
   }
   public boolean tryLock(String key) {
      if (!StringUtils.isEmpty(key)) {
         key = key.toUpperCase();
         synchronized (key.intern()) {
            if (!this.obj.containsKey(key)) {
               lock(key);
               //获取当前线程
               long id = Thread.currentThread().getId();
               threadObj.put(key, id);
               return true;
            }
         }